简体   繁体   中英

C# Add Accept header to HttpClient

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?

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.

There's no difference in the end result, as long as the names and values are correct.

The HTTP standard specifies that certain headers have a quality factor , hence the name MediaTypeWithQualityHeaderValue . It's a MediaType header value that can have a Quality factor. You can pass the quality factor if you use the MediaTypeWithQualityHeaderValue Constructor (String, Double) constructor

The Accept header section in the standard shows several examples that use the quality factor. For example,

The example

   Accept: audio/*; q=0.2, audio/basic

SHOULD be interpreted as "I prefer audio/basic, but send me any audio type if it is the best available after an 80% mark-down in quality."

You could write that with

var requestAccepts=client.DefaultRequestHeaders.Accept;
requestAccepts.Add(new MediaTypeWithQualityHeaderValue("audio/*",0.2));
requestAccepts.Add(new MediaTypeWithQualityHeaderValue("audio/basic"));

Or you can enter the raw header value with :

client.DefaultRequestHeaders.Add("Accept", "audio/*; q=0.2, audio/basic");

我认为不存在差异,它只是通过Accept等属性添加标准头文件的一种简单方法,也方便通过Add方法添加自定义头文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM