-->

C# HttpClient, getting error Cannot add value beca

2020-08-13 08:14发布

问题:

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?

回答1:

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");


回答2:

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()



回答3:

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");


回答4:

  var settings = new JsonSerializerSettings()
        {
            DateFormatHandling =
                DateFormatHandling.MicrosoftDateFormat
        };
        var serializedString = JsonConvert.SerializeObject(data, settings);

        var conent = new StringContent(serializedString);
        conent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await this.httpClient.PostAsync(requestUri, conent).ConfigureAwait(false);

        T requestResult = default(T);
        if (response.IsSuccessStatusCode)
        {
            response.EnsureSuccessStatusCode();
            requestResult = await response.Content.ReadAsAsync<T>();
        }


标签: c#