There's a bug in the ReadAsStringAsync method that prevents a Content-Type looking like application/json; charset="utf-8"
from being read. It doesn't look like there's a framework fix for it yet, but are there any workarounds?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Before you read the response, you need to remove the quotes:
var contentType = response.Content.Headers.ContentType;
if (contentType.CharSet?.Contains('"') == true) {
contentType.CharSet = contentType.CharSet.Replace("\"", "");
}
Here's the complete DelegatingHandler that I'm using:
public class StripCharSetQuotesHandler : DelegatingHandler
{
public StripCharSetQuotesHandler(HttpClientHandler innerHandler) {
: base(innerHandler)
{
// Nothing additional.
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
var response = await base.SendAsync(request, cancellationToken);
var contentType = response.Content.Headers.ContentType;
if (contentType.CharSet?.Contains('"') == true) {
contentType.CharSet = contentType.CharSet.Replace("\"", "");
}
return response;
}
}
You want to make sure that you're stripping the quotes as close to the HttpClientHandler
as possible, which is why the constructor accepts an HttpClientHandler
and not an HttpMessageHandler
.