相关疑难解决方法(0)

如何从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, string requestUri, T value)
    { …
Run Code Online (Sandbox Code Playgroud)

asp.net json httpclient utf-8 asp.net-web-api

8
推荐指数
2
解决办法
5442
查看次数

标签 统计

asp.net ×1

asp.net-web-api ×1

httpclient ×1

json ×1

utf-8 ×1