How to accept a charset containing quotes

2019-08-18 00:53发布

问题:

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.



标签: c# .net-core