【问题标题】:How to accept a charset containing quotes如何接受包含引号的字符集
【发布时间】:2018-06-12 15:00:14
【问题描述】:

有一个bug in the ReadAsStringAsync method 可以防止读取看起来像application/json; charset="utf-8" 的Content-Type。看起来还没有针对它的框架修复,但是有什么解决方法吗?

【问题讨论】:

  • @Programmer:我在下面的答案中添加了完整的DelegatingHandler;这对你有用吗?

标签: c# .net-core


【解决方案1】:

在阅读回复之前,您需要删除引号:

var contentType = response.Content.Headers.ContentType;
if (contentType.CharSet?.Contains('"') == true) {
    contentType.CharSet = contentType.CharSet.Replace("\"", "");
}

这是我正在使用的完整 DelegatingHandler:

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;
    }

}

您要确保将引号尽可能靠近HttpClientHandler,这就是构造函数接受HttpClientHandler 而不是HttpMessageHandler 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多