Friday, July 28, 2017

ASP.NET : Misused header name. Make sure request headers are used

The full error is:

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

This is when I use HttpClient with .NET 4.5 and try something like:

client.DefaultRequestHeaders.Add("Contact-Type", ...);

And so began a long and painful journey to figure out to to fix this because the external web API wouldn't work without "Content-Type" as a header.

There is so much garbage out there :-(

After some research, Content-Type is part of Content - the name pretty much implies that - so use HttpContent.

using (var client = new HttpClient())
{
  // Adding contentType to client as header gives "Misused header name. Make   sure request headers are used 
with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent 
  // objects."

  client.DefaultRequestHeaders.Add("Authorization", "Bearer abc...123");

  HttpResponseMessage response;
  
  // Construct an HttpContent from the data
  HttpContent hc = new StringContent(data);
  hc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  response = client.PostAsync(baseAddress, hc).Result;

  response.EnsureSuccessStatusCode();
               
  var result = response.Content.ReadAsStringAsync().Result;
}


Enjoy!

10 comments:

Boris said...

Saved a lot of time with this. Thank you!

Anonymous said...

helped me as well. Thank you

Anonymous said...

This really worked. Thanks for sharing.

Unknown said...

TYVM!

Vaisakh said...

Its worked

Vaisakh said...

Its worked

Geoff D said...

Found this after a couple days of trying. I had my code working in about 3 minutes. Thank you!

Geoff D said...

I spent a couple days trying different solutions, nothing worked. Found this and had it working in about 5 minutes. Thank you so much!

arjun rajan said...

You are a hero!!! Thank you soo much.

Anonymous said...

Thank you for this!
You earned my respect.