How to accept a charset containing quotes

2019-08-18 00:51发布

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?

标签: c# .net-core
1条回答
Evening l夕情丶
2楼-- · 2019-08-18 01:28

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.

查看更多
登录 后发表回答