C# HttpClient, getting error Cannot add value because header 'content-type' does not support multiple values
Haven't got .NET 4.5 ready, but according to HttpContentHeaders.ContentType
and MediaTypeHeaderValue
, it should look something like this:
content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
This error implies that you try to add an header that has already been added to the DefaultRequestHeaders
(not only content-type
header, but any other header that do not support multiple values).
In my case, I was initiating the headers from two different places and accidentally added the same key header twice (for example content-type
or Authentication
).
Inside the startup.cs
, IHttpClientFactory
(documentation) like:
services.AddHttpClient("MyHttpClient", client =>
{
client.BaseAddress = new Uri("https://www.google.co.il/");
client.Timeout = new TimeSpan(0, 1, 0);
client.DefaultRequestHeaders.Add("content-type", "application/json"));
client.DefaultRequestHeaders.Add("Authorization", "some values"));
});
And got updated inside the client service:
HttpClient httpClient = this._httpClientFactory.CreateClient("MyHttpClient");
httpClient.DefaultRequestHeaders.Add("content-type", "application/json")); //Throws Exception!
httpClient.DefaultRequestHeaders.Add("Authorization", "some values")); //Throws Exception!
UPDATE:
In cases you want to be sure that you can add header you can use carefully the DefaultRequestHeaders.Clear()
As soon as you assign a text value to the HttpContent by doing this-
HttpContent content = new StringContent(text);
the content type is automatically set for that content. This content type (in case of String Content) is - {text/plain; charset=utf-8}
So in the next step when you try to explicitly set the Content-Type header you get the error- Cannot add value because header 'Content-Type' does not support multiple values.
There are three ways by which you can set the content type and avoid this error:
Option 1. Specify the content type while setting the content
HttpContent content = new StringContent(text, System.Text.Encoding.UTF8, "text/html");
Option 2. Setting the ContentType property
HttpContent content = new StringContent(text);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
Option 3. First remove the automatically assigned content-type header and then add that header again.
HttpContent content = new StringContent(text);
content.Headers.Remove("content-type");
content.Headers.Add("content-type", "text/html");