217

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();

2 Answers 2

328

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>();
Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
These days you probably want var response = await client.SendAsync instead of ContinueWith and task.Wait()
Please note for best performance, you shouldn't instantiate an HTTP client like this. You can read more about this here stackoverflow.com/a/15708633/1406930
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.")
67

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

6 Comments

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.
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.
How can I later change this header? If I use another .Add("apikey","yyy"), it become "apikey: xxxxxxxxxyyy"
you can read headers and update?
@HamidZ same problem here. I solved it doing .Clear then .Add again.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.