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:
Saved a lot of time with this. Thank you!
helped me as well. Thank you
This really worked. Thanks for sharing.
TYVM!
Its worked
Its worked
Found this after a couple days of trying. I had my code working in about 3 minutes. Thank you!
I spent a couple days trying different solutions, nothing worked. Found this and had it working in about 5 minutes. Thank you so much!
You are a hero!!! Thank you soo much.
Thank you for this!
You earned my respect.
Post a Comment