【发布时间】:2014-04-18 19:41:41
【问题描述】:
我有一个问题 HttpClient.PostAsJsonAsync()
除了“Content-Type”标头中的“application/json”之外,该方法还添加了“charset=utf-8”
所以标题看起来像这样:
内容类型:应用程序/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)
{
return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter());
}
}
【问题讨论】:
-
更多更好的解决方案:stackoverflow.com/questions/40273638/…
标签: asp.net json utf-8 asp.net-web-api httpclient