Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient, getting error Cannot add value because header 'content-type' does not support multiple values

Tags:

c#

HttpClient serviceClient = new HttpClient();
serviceClient.DefaultRequestHeaders.Add("accept", "Application/JSON");

HttpContent content = new StringContent(text);
content.Headers.Add("content-type", "text/html");

var response = await serviceClient.PostAsync(new Uri(_serviceUrl), content);

This is my code. I want to do a POST, and set the content type to text/html, but when I do this I get the above error.

I can set the content type it seems via content.Headers.ContentType but I don't know how to specifcy "text/html" if I do that. Can anyone help?

like image 776
NibblyPig Avatar asked May 02 '13 11:05

NibblyPig


2 Answers

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");
like image 97
CodeCaster Avatar answered Sep 21 '22 15:09

CodeCaster


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");
like image 24
Saurabh R S Avatar answered Sep 20 '22 15:09

Saurabh R S