207

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();
Yarek T
  • 9,715
  • 2
  • 28
  • 38
Ryan Pfister
  • 3,176
  • 4
  • 24
  • 26

2 Answers2

316

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();
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • 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. – Talon Feb 27 '15 at 08:55
  • 25
    @Talon 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. – Darrel Miller Feb 27 '15 at 15:14
  • 22
    These days you probably want `var response = await client.SendAsync` instead of `ContinueWith` and `task.Wait()` – Michael Parker Aug 21 '17 at 14:28
  • 6
    Please note for best performance, you shouldn't instantiate an HTTP client like this. You can read more about this here https://stackoverflow.com/a/15708633/1406930 – ScottBurfieldMills Nov 18 '18 at 20:27
  • Remember to dispose of HttpRequestMessage, also HttpClient (disposable as well) should be created as few times as possible: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#remarks ("HttpClient is intended to be instantiated once and re-used throughout the life of an application.") – user1713059 Feb 25 '20 at 15:47
56

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");      
Aage
  • 5,932
  • 2
  • 32
  • 57
Taran
  • 2,895
  • 25
  • 22
  • 10
    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. – Flydog57 Feb 25 '19 at 18:13
  • 1
    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. – Zimba Dec 16 '19 at 14:53
  • 1
    How can I later change this header? If I use another .Add("apikey","yyy"), it become "apikey: xxxxxxxxxyyy" – Hamid Z Jan 17 '22 at 08:45
  • you can read headers and update? – Taran Mar 16 '22 at 14:06
  • This is the correct way to use it in modern .NET Core/6+ if your injecting the client using "services.AddHttpClient" – shawty May 04 '22 at 20:12
  • @HamidZ same problem here. I solved it doing .Clear then .Add again. – Ivan Ferrer Villa Jan 11 '23 at 17:53