Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET HttpClient: How to set the request method dynamically?

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";
like image 692
Steve Avatar asked Dec 09 '16 17:12

Steve


2 Answers

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.

like image 78
CodeFuller Avatar answered Sep 24 '22 03:09

CodeFuller


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();

    }
}
}
like image 38
Mark D. Avatar answered Sep 22 '22 03:09

Mark D.