简体   繁体   English

C# HttpClient,出现错误无法添加值,因为标头“内容类型”不支持多个值

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

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.我想做一个 POST,并将内容类型设置为 text/html,但是当我这样做时,我得到了上述错误。

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.我可以通过content.Headers.ContentType设置它看起来的内容类型,但如果我这样做,我不知道如何指定“text/html”。 Can anyone help?任何人都可以帮忙吗?

尚未准备好 .NET 4.5,但根据HttpContentHeaders.ContentTypeMediaTypeHeaderValue ,它应该如下所示:

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).此错误意味着您尝试添加已添加到DefaultRequestHeaders标头(不仅是content-type标头,还包括任何其他不支持多个值的标头)。


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 ).就我而言,我从两个不同的地方启动标头,不小心添加了两次相同的密钥标头(例如content-typeAuthentication )。

Inside the startup.cs , IHttpClientFactory ( documentation ) like:startup.csIHttpClientFactory文档)如:

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()更新:如果您想确保可以添加标头,您可以谨慎使用DefaultRequestHeaders.Clear()

As soon as you assign a text value to the HttpContent by doing this-只要您通过执行此操作为 HttpContent 分配文本值 -

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}此内容类型(在字符串内容的情况下)是 - {text/plain; charset=utf-8} {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.因此,在下一步中,当您尝试显式设置 Content-Type 标头时,您会收到错误 -无法添加值,因为标头“Content-Type”不支持多个值。

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选项 1.设置内容时指定内容类型

HttpContent content = new StringContent(text, System.Text.Encoding.UTF8, "text/html");

Option 2. Setting the ContentType property选项 2.设置 ContentType 属性

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.选项 3。首先删除自动分配的内容类型标头,然后再次添加该标头。

HttpContent content = new StringContent(text);  
content.Headers.Remove("content-type");  
content.Headers.Add("content-type", "text/html");
  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>();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用c#HttpClient发送Content-Type标头 - Can't send Content-Type header with c# HttpClient C# 带有自定义标头的 HttpClient POST 请求发送不正确的 Content-Type header 字段 - C# HttpClient POST Request with Custom Headers sends incorrect Content-Type header field 将内容类型标头添加到 httpclient GET 请求 - Add content-type header to httpclient GET request c# HttpClient post response content-type application/json - c# HttpClient post response content-type application/json 如何在C#中使用具有复杂内容类型的HttpClient? - How to use HttpClient with complex content-type in c#? HttpClient 不返回 Content-Type - HttpClient does not return Content-Type 如何将配置文件参数添加到 C# 中的内容类型标头? - How do I add the profile parameter to the content-type header in C#? C#:在HTTP中使用Content-Type标头发送参数 - C#: Sending parameter with Content-Type Header in HTTP 自定义消息编码器c#中的错误“找不到来自MTOM消息的Content-Type标头” - Error “Content-Type header from MTOM message not found” in custom message encoder c# 使用 C# HttpClient 发送的 HEAD 请求返回的 Content-Type 不正确; 但是,邮递员返回正确的 Content-Type - Content-Type returned by HEAD request sent using C# HttpClient is incorrect; however, Postman returns the correct Content-Type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM