微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – 如何从HttpClient.PostAsJsonAsync()生成的Content-Type标头中删除charset = utf8?

我有一个问题
HttpClient.PostAsJsonAsync()

除了“Content-Type”标题中的“application / json”之外,该方法添加了“charset = utf-8”

所以标题看起来像这样:

Content-Type:application / json;字符集= utf-8的

虽然ASP.NET WebAPI对此标头没有任何问题,但我发现我作为客户端工作的其他WebAPI不接受带有此标头的请求,除非它只是application / json.

无论如何在使用PostAsJsonAsync()时从Content-Type中删除“charset = utf-8”,还是应该使用其他方法

解:
Yishai的积分!

using System.Net.Http.Headers;

public class NoCharSetJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
   public override void SetDefaultContentHeaders(Type type,HttpContentHeaders headers,MediaTypeHeaderValue mediaType)
   {
       base.SetDefaultContentHeaders(type,headers,mediaType);
       headers.ContentType.CharSet = "";
   }
}

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client,string requestUri,T value,CancellationToken cancellationToken)
    {
        return await client.PostAsync(requestUri,value,new NoCharSetJsonMediaTypeFormatter(),cancellationToken);
    }

    public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client,T value)
    {
        return await client.PostAsync(requestUri,new NoCharSetJsonMediaTypeFormatter());
    }
}

解决方法

您可以从JsonMediaTypeFormatter派生并覆盖SetDefaultContentHeaders.

调用base.SetDefaultContentHeaders()然后清除headers.ContentType.CharSet

然后根据以下代码编写自己的扩展方法

public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client,CancellationToken cancellationToken)
{
    return client.PostAsync(requestUri,new JsonMediaTypeFormatter(),cancellationToken);
}

本质上是这样的:

public static Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client,CancellatioNToken cancellationToken)
{
    return client.PostAsync(requestUri,cancellationToken);
}

原文地址:https://www.jb51.cc/aspnet/248698.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐