Search code examples
c#.nethttpwebrequestdotnet-httpclient

.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";

Solution

  • 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.