50

I'm currently using the System.Net.Http.HttpClient for cross platform support.

I read that it is not a good practice to instantiate a HttpClient object for each request and that you should reuse it whenever possible.

Now I have a problem while writing a client library for a service. Some API calls need to have a specific header, some MUST not include this specific header.

It seems that I can only manipulate the "DefaultRequestHeaders" which will be send with each request.

Is there an option when actually making the request with e.g. "client.PostAsync()" to modify the headers only for the specific request?

(Info: Requests can be multi threaded).

Thanks in advance!

coalmee
  • 1,334
  • 2
  • 16
  • 27

2 Answers2

82

Yes, you can create a new HttpRequestMessage, set all the properties you need to, and then pass it to SendAsync.

var request = new HttpRequestMessage() {
   RequestUri = new Uri("http://example.org"),
   Method = HttpMethod.Post,
   Content = new StringContent("Here is my content")
}
request.Headers.Accept.Add(...);  // Set whatever headers you need to

var response = await client.SendAsync(request);
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • @user2864740 That's strange. It should be there in both the .net 4.5.1 and PCL versions https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.sendasync(v=vs.118).aspx – Darrel Miller Dec 01 '15 at 19:40
  • 1
    Oh, my mistake.. I was looking at `Get..` :} – user2864740 Dec 01 '15 at 19:42
  • 1
    @DarrelMiller what happens when the client issues multiple HttpRequestMessages? For instance, an access token needs to be passed in the header to hit an api, I make a request and then you make a request (we are both users of a client site) - the HttpClient instance is shared between the requests since its static. Lets say my request takes longer than yours, does that cause problems? – crizzwald Nov 30 '16 at 16:53
  • 3
    @crizzwald Nope. The SendAsync method is thread safe. Multiple threads can each send their own HttpRequestMessage instance to the same HttpClient instance. The correct Task will continue when the response is received. – Darrel Miller Nov 30 '16 at 16:57
  • @DarrelMiller oh now thats awesome. this totally solves the TIME_WAIT issue i've been reading about to which now HttpClient can be used in a highly scalable fashion. thanks!! – crizzwald Nov 30 '16 at 17:15
  • 1
    @FrancescoC.There's a chapter about HttpClient in our WebAPI book. It's available free online http://chimera.labs.oreilly.com/books/1234000001708/ch14.html There may be some useful information there. – Darrel Miller Sep 11 '17 at 00:48
1

Use HttpContent.Headers. Simply create HttpContent instance with required headers and pass it to PostAsync method.

SuMMeR
  • 99
  • 2