Adding Http Headers to HttpClient
Asked Answered
L

2

212

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();
Lesbian answered 18/8, 2012 at 23:12 Comment(0)
F
323

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

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();
Fecund answered 19/8, 2012 at 0:31 Comment(5)
Careful with this method. I have used it now to check if a bunch of urls were still available. A bunch of them returned 406 error purely because they did not have a "text/plain" mediaType to return.Osmose
@Osmose That's what 406 means. The client asked for a media type that the server doesn't support. If you don't care what media type you get, then don't ask for one. The OP was simply asking how to add headers to a request. I just picked a random example.Fecund
These days you probably want var response = await client.SendAsync instead of ContinueWith and task.Wait()Springhouse
Please note for best performance, you shouldn't instantiate an HTTP client like this. You can read more about this here https://mcmap.net/q/76441/-do-httpclient-and-httpclienthandler-have-to-be-disposed-between-requestsBioscopy
Remember to dispose of HttpRequestMessage, also HttpClient (disposable as well) should be created as few times as possible: learn.microsoft.com/en-us/dotnet/api/… ("HttpClient is intended to be instantiated once and re-used throughout the life of an application.")Terrell
C
58

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      
Crystallize answered 14/2, 2019 at 17:3 Comment(6)
I believe that that adds the header to all messages send by that HttpClient going forward. That contradicts the OP's point: "How do I do that for an individual request (as opposed to on the HttpClient to all future requests)?" HttpClient instances are designed to be created once and used many times.Tapeworm
To set custom headers on a request, build a request with the custom header before passing it to httpclient to send to http server. Default header is set on httpclient to send on every request to the server.Maddalena
How can I later change this header? If I use another .Add("apikey","yyy"), it become "apikey: xxxxxxxxxyyy"Ariana
you can read headers and update?Crystallize
This is the correct way to use it in modern .NET Core/6+ if your injecting the client using "services.AddHttpClient"Resh
@HamidZ same problem here. I solved it doing .Clear then .Add again.Tambourine

© 2022 - 2024 — McMap. All rights reserved.