我有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)