BlackMushroom
BlackMushroom

Reputation: 103

Asp.Net Core API response wrong json encoding using IIS

I have an API in ASP Core 3.0 and an MVC client application in ASP Core 2.2. In the client application, I use HttpClient to call API methods and ReadAsStringAsync() to read responses and it works fine in debug.

When I publish to IIS on a real server, JSON responses are not properly read using response.Content.ReadAsStringAsync(). A string is created but JSON is unreadable, probably wrongly encoded, so I'm not able to convert it to an object.

I checked the response with Fiddler and everything looks fine, header Content-Type: application/json; charset=utf-8 is present and JSON looks good. I don't know what kind of IIS specific behaviour produces this. I tried on a local instance of IIS and didn't reproduce this issue.

I've tried using Newtonsoft.Json to encode the API response content and also tried adding [Produces("application/json")] to the API controller, the problem is still there.

Here is an example of what an API method returns :

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

And this how I read the response

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() is a custom wrapper for HttpClient.PostAsync()

Upvotes: 0

Views: 2214

Answers (1)

BlackMushroom
BlackMushroom

Reputation: 103

After a few tests, I understood the problem appeared only when I added this header to my HttpClient instance :

Accept-Encoding: gzip, deflate

Removing this header solved the problem. Now I have to figure out how to use compression with IIS, I'm going back to Microsoft docs ;)

Upvotes: 1

Related Questions