Search code examples
c#asp.net-web-apidotnet-httpclient

Adding Http Headers to HttpClient


I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible.

var client = new HttpClient();
var task =
    client.GetAsync("http://www.someURI.com")
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Solution

  • Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

    static HttpClient _client = new HttpClient();
    
    using var request = new HttpRequestMessage() {
        RequestUri = new Uri("http://www.someURI.com"),
        Method = HttpMethod.Get,
    };
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
    using var response = await client.SendAsync(request);
    var jsonObject = await response.Content.ReadAsAsync<JsonObject>();