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:

  1. Saved a lot of time with this. Thank you!

    ReplyDelete
  2. helped me as well. Thank you

    ReplyDelete
  3. This really worked. Thanks for sharing.

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

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

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

    ReplyDelete
  7. Thank you for this!
    You earned my respect.

    ReplyDelete