【问题标题】:Asp.Net Core API response wrong json encoding using IIS使用 IIS 的 Asp.Net Core API 响应错误的 json 编码
【发布时间】:2020-04-20 02:21:44
【问题描述】:

我在 ASP Core 3.0 中有一个 API,在 ASP Core 2.2 中有一个 MVC 客户端应用程序。在客户端应用程序中,我使用 HttpClient 调用 API 方法并使用 ReadAsStringAsync() 读取响应,并且在调试中运行良好。

当我在真实服务器上发布到 IIS 时,无法使用 response.Content.ReadAsStringAsync() 正确读取 JSON 响应。创建了一个字符串,但 JSON 不可读,可能编码错误,因此我无法将其转换为对象。

我用 Fiddler 检查了响应,一切看起来都很好,标题 Content-Type: application/json; charset=utf-8 存在并且 JSON 看起来不错。我不知道什么样的 IIS 特定行为会产生这种情况。我在 IIS 的本地实例上进行了尝试,但没有重现此问题。

我尝试使用 Newtonsoft.Json 对 API 响应内容进行编码,还尝试将 [Produces("application/json")] 添加到 API 控制器,问题仍然存在。

以下是 API 方法返回的示例:

return Ok(new UserDto
{
    Login = user.Login,
    IdAccountUser = user.IdAccountUser,
    Prenom = user.Prenom,
    Nom = user.Nom,
    Token = tokenString
});

这就是我阅读回复的方式

HttpResponseMessage response = await _apiHttpClient.Post("users/authentication", user);

string logDetail = string.Empty;

if (response?.Content != null)
{
    if (response.IsSuccessStatusCode)
    {
        string json = null;
        try
        {
            json = await response.Content.ReadAsStringAsync();
            // Deserialization fails here because of invalid JSON
            user = JsonConvert.DeserializeObject<UserDto>(json);
            bool authenticationSuccessful = await AuthenticateUser(user);

            if (authenticationSuccessful)
                return string.IsNullOrEmpty(model.ReturnUrl) ? await Index() : Redirect($"~{model.ReturnUrl}");
        }
        catch (JsonReaderException ex)
        {
            _logger.LogError(ex, "Erreur de lecture du JSON : {0}", json);
        }
    }
    else
        logDetail = $"Code HTTP réponse: {response.StatusCode}";
}

_apiHttpClient.Post() 是 HttpClient.PostAsync() 的自定义包装器

【问题讨论】:

  • 我猜几年前我们也遇到过同样的问题。我现在只记得我们已经更改了一些 WebDav IIS 设置以包含所有方法,即 API 服务器上的发布、放置、删除等
  • 我可以尝试,但我不确定它会改变什么,因为当我使用 Postman 调用我的 API 方法时 JSON 是有效的。我认为问题更多的是客户端,并且与 HttpClient 和 HttpResponseMessage 有关。
  • @Prany 感谢您的评论,但在我的情况下,这似乎是一个请求标头问题:当我删除“Accept-Encoding: gzip, deflate”标头时,json 是可读的。
  • 别担心,我认为您可以在下面为社区发表评论:)

标签: c# json asp.net-core iis asp.net-web-api


【解决方案1】:

经过几次测试,我明白只有当我将此标头添加到我的 HttpClient 实例时才会出现问题:

Accept-Encoding: gzip, deflate

删除此标头解决了问题。现在我必须弄清楚如何在 IIS 中使用压缩,我要回到 Microsoft 文档 ;)

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 2020-11-27
    • 2018-12-19
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多