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?
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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With