C# Add Accept header to HttpClient

evilSnobu picture evilSnobu · Nov 8, 2017 · Viewed 35.1k times · Source

What is the difference between these two calls? My end goal is to have Accept: application/json sent over the wire, not to append to some default set of other MIME types.

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");

vs.

client.DefaultRequestHeaders
  .Accept
  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

My CLR is .NET Core 2.0.

Sniffing the wire reveals no difference:

# just .Add("Accept"...
~ % nc -l 8000
GET / HTTP/1.1
Connection: Keep-Alive
Accept: application/json
[...]

# with MediaTypeWithQualityHeaderValue
~ % nc -l 8000
GET / HTTP/1.1
Connection: Keep-Alive
Accept: application/json
[...]

So, outside the bizarre naming of that type, nothing else to gain here right?

Answer

Barr J picture Barr J · Nov 8, 2017

There is no difference.

DefaultRequestHeaders.Accept is a collection of string type, where you can add your header to accept using the new instance of MediaTypeWithQualityHeaderValue.

client.DefaultRequestHeaders is a dictionary that accepts key for and value for the request header and matches the results according to them.

DefaultRequestHeaders

has overloads.

The only thing that differs between them, is the fact that DefaultRequestHeaders.Accept will require you to initialize a new instance of MediaTypeWithQualityHeaderValue class, resulting in another reference type in the heap, while client.DefaultRequestHeaders will add the data to the dictionary, removing the cost of resources and the need to initialize a new instance.

It is really up to the user as to how and what to use.