【问题标题】:Unable to receive response using RestEase无法使用 RestEase 接收响应
【发布时间】:2018-05-22 13:13:58
【问题描述】:

收到的响应如下:

'UTF8' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.

【问题讨论】:

  • 您使用的是 .net 核心还是“完整”框架?
  • @AntonGorbunov - 完整的框架。我不认为这是重复的,因为这个问题必须通过 RestEase 而不是 HttpClient 来解决

标签: c# .net rest encoding utf-8


【解决方案1】:

我认为问题在于服务器在标头中返回了错误的字符集名称。取而代之的是 charset=utf-8 它设置为 charset=utf8

而且在反序列化的时候,HttpClient(RestEase 使用它)不明白要使用什么编码。

要解决此问题,您需要添加一个新的提供程序,该提供程序将指向通常的 UTF8 编码。

您应该在“全局”级别添加代码(例如Main 方法):

EncodingProvider provider = new CustomUtf8EncodingProvider();
Encoding.RegisterProvider(provider);

类,女巫为错误的字符集名称返回 UTF8 编码:

public class CustomUtf8EncodingProvider : EncodingProvider
{
    public override Encoding GetEncoding(string name)
    {
        return name == "utf8" ? Encoding.UTF8 : null;
    }

    public override Encoding GetEncoding(int codepage)
    {
        return null;
    }
}

我是这样检查的

EncodingProvider provider = new CustomUtf8EncodingProvider(); 
Encoding.RegisterProvider(provider); //If comment this row - you get exception "'UTF8' is not a supported encoding name...", if uncomment - it works good
Console.WriteLine(Encoding.GetEncoding("utf8").GetString(new byte[]{0x31,0x32,0x33}));

注意

它仅适用于 .net 4.6 或更高版本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2019-02-04
    • 2013-05-13
    • 2020-09-16
    相关资源
    最近更新 更多