Home > Software design >  What is the .NET Core HttpRequest Headers priority?
What is the .NET Core HttpRequest Headers priority?

Time:10-27

Currently I am doing a http request sending task. I know we have different ways to add headers to the request.

  1. HttpClient.DefaultRequestHeaders
  2. HttpRequestMessage.Headers
  3. HttpContent.Headers

If I have a custom header called A, which header collection of (1, 2, 3) should I insert the A to?

if (1,2), (1,3), OR (2,3) contains same key e.g. both 1 and 2 has "Host", what is the priority of them? will one replace others? or it will throw an exception?

CodePudding user response:

This is a good question. Each of the Headers collection has a dedicated purpose (as it was mentioned by other commenters as well).

Purposes

  • DefaultRequestHeaders can be used to set headers that are intended to be reused in multiple requests
  • Headers of HttpRequestMessage can be used to set headers like Accept, Accept-Encoding, Authorization, Cookie, etc
  • Headers of HttpContent can be used to set headers like Content-Disposition, Content-Range, Content-Length, Content-Type, etc.

Setting standard headers

Those headers that set on DefaultRequestHeaders can be overwritten by the Headers of HttpRequestMessage for an individual request.

If you try to set

  • the Content-Type header on HttpRequestMessage
  • or the Accept header on HttpContent

then you will receive an InvalidOperationException:

System.InvalidOperationException: 'Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'

Setting custom headers

If you try to set the same arbitrary (not standard) header on HttpRequestMessage and on HttpContent then both values will be sent.


Here I have detailed this topic in a bit more depth.

  • Related