Search code examples
c#dotnet-httpclient

Is there a way to parameterize the HTTP method when using System.Net.Http.HttpClient?


I'm using HttpClient in .Net core 3.1. Most of my requests follow a similar pattern regardless of the HTTP method used:

  • build URL
  • build (optional) JSON payload
  • send request
  • await response
  • check status code
  • parse (optional) JSON response

so I've built a wrapper function that does all these things, and it takes the HTTP method as a parameter. However, when it comes to the "send request" step, I need to use a switch statement to invoke the appropriate method on HttpClient to invoke.

I'm sure that under the skin, get GetAsync() PostAsync() etc. are calling the same underlying function and passing the Http method as a parameter. but I can't see any way of calling it like this from the outside. It seems a strange omission as in my experience most HTTP libraries work that way.


Solution

  • Hope this will help you.

    // For JsonConvert use Newtonsoft.Json
    string url = "YourURL";
    string body = JsonConvert.SerializeObject(BodyModel);
    string headerParameter = "ASD123456789";
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
    client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
    {
        Content = new StringContent(body, Encoding.UTF8, "application/json")
    };
    HttpResponseMessage response = await client.SendAsync(request);
    if ((int)response.StatusCode == 200)
    {
        string responseString = await response.Content.ReadAsStringAsync();
        ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
    }