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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....