Currently I am doing a http request sending task. I know we have different ways to add headers to the request.
HttpClient.DefaultRequestHeaders
HttpRequestMessage.Headers
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 requestsHeaders
ofHttpRequestMessage
can be used to set headers likeAccept
,Accept-Encoding
,Authorization
,Cookie
, etcHeaders
ofHttpContent
can be used to set headers likeContent-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 onHttpRequestMessage
- or the
Accept
header onHttpContent
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.