Home > Blockchain >  C# Setting custom headers to httpclient gives error as misused header name
C# Setting custom headers to httpclient gives error as misused header name

Time:12-09

I am trying to set custom headers like these

x-my-header:somecustomval
content-type:application/vnd.status json
.
.
.
other headers

There are two approaches I tried, using a dictionary of headers

#1

_httpClient.DefaultRequestHeaders.Clear();

foreach (var h in headers)
{
  _httpClient.DefaultRequestHeaders.Add(h.Key.ToString(), h.Value.ToString());
}

#2

HttpRequestMessage req = new HttpRequestMessage();

foreach (var h in headers)
{
  req.Headers.Add(h.Key.ToString(), h.Value.ToString());
}

The error I am getting in both approaches is this:

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

How do you set the headers for a POST in the HttpClient in C# net core 3.1? Can you not set custom headers?

CodePudding user response:

Use the HttpHeaders.TryAddWithoutValidation method in either of your attempts.

Internally the default HttpHeaders.Add will try to validate that you are adding a known HTTP header and will fail if not valid.

Reference HttpHeaders

  • Related