Search code examples
c#.nethttpwebrequestdotnet-httpclient

How does .Net HttpClient manage to have multiple Media Types


I am implementing an HttpWebRequest and noticed that the Accept property is of type string

 webRequest.Accept = "application/json";

The implementation of HttpClient has it's Accept as type of HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>

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

Which means you can Add as much Media types to it as you want.

But according to this question, the standard only allows you to accept 1 Content or Media Type.

So, how is HttpClient able to support multiple Media Types?


Solution

  • The question you linked to is talking about the Content-Type header in responses.

    You're looking at the Accept header in requests.

    The server decides which specific content type (which may or may not match any from the Accept header) to respond with. This is a process referred to as Content Negotiation.

    The specifics of how this works on the server side depends on the server technology being used. Here's an introduction to how it works in ASP.Net MVC Web API