我有一个问题
HttpClient.PostAsJsonAsync()
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); }