9

How can one use HttpClient and set the method dynamically without having to do something like:

    public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
    {
        HttpResponseMessage response;

        using (var client = new HttpClient())
        {
            switch (method.ToUpper())
            {
                case "POST":
                    response = await client.PostAsync(url, content);
                    break;
                case "GET":
                    response = await client.GetAsync(url);
                    break;
                default:
                    response = null;
                    // Unsupported method exception etc.
                    break;
            }
        }

        return response;
    }

At the moment it looks like you would have to use:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
2
  • 1
    You can httprequestmessage and set the method, url and content. Then use send method of httpclient Commented Dec 9, 2016 at 17:47
  • Note that you should not new HttpClient() per request, or you can exhaust your socket pool at scale. Use a single static instance. Commented Jul 11, 2017 at 18:30

4 Answers 4

9

HttpRequestMessage contains constructor taking instance of HttpMethod but there is no ready constructor that converts HTTP method string to HttpMethod, so you can't avoid that switch (in one form or another).

However you should not have duplicated code under different switch cases, so implementation would be something like this:

private HttpMethod CreateHttpMethod(string method)
{
    switch (method.ToUpper())
    {
        case "POST":
            return HttpMethod.Post;
        case "GET":
            return HttpMethod.Get;
        default:
            throw new NotImplementedException();
    }
}

public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
{
    var request = new HttpRequestMessage(CreateHttpMethod(method), url)
    {
        Content = content
    };

    return await client.SendAsync(request);
}

If you don't like that switch you could avoid it using Dictionary with method string as a key, however such solution will not be simpler or faster.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also pass in HttpMethod httpMethod as a parameter, and then do new HttpRequestMessage(httpMethod, url)
9

but there is no ready constructor that converts HTTP method string to HttpMethod

Well that's not true any longer...1

public HttpMethod(string method);

Can be used like this:

var httpMethod = new HttpMethod(method.ToUpper());

Here is working code.

using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace MyNamespace.HttpClient
{
public static class HttpClient
{
    private static readonly System.Net.Http.HttpClient NetHttpClient = new System.Net.Http.HttpClient();
    static HttpClient()
    {}

    public static async System.Threading.Tasks.Task<string> ExecuteMethod(string targetAbsoluteUrl, string methodName, List<KeyValuePair<string, string>> headers = null, string content = null, string contentType = null)
    {
        var httpMethod = new HttpMethod(methodName.ToUpper());

        var requestMessage = new HttpRequestMessage(httpMethod, targetAbsoluteUrl);

        if (!string.IsNullOrWhiteSpace(content) || !string.IsNullOrWhiteSpace(contentType))
        {
            var contentBytes = Encoding.UTF8.GetBytes(content);
            requestMessage.Content = new ByteArrayContent(contentBytes);

            headers = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Content-type", contentType)
            };
        }

        headers?.ForEach(kvp => { requestMessage.Headers.Add(kvp.Key, kvp.Value); });

        var response = await NetHttpClient.SendAsync(requestMessage);

        return await response.Content.ReadAsStringAsync();

    }
}
}

2 Comments

the msdn link is not accessible now. Please change to the learn.microsoft.com/en-us/dotnet/api/…
@ Tsahi Ahser - thanks for editing the resource link!
1

.Net Core

var hc = _hcAccessor.HttpContext;

var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');

Comments

0

.NET Core later versions:

HttpClient client = new HttpClient();

// Add headers etc...

// Post
response = await client.PostAsync(uri, content);

// Get
response = await client.GetAsync(uri);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.