Issues with HttpClient and Encoding in Azure but not on Localhost Environment
Hi guys,
I wasn't sure if this issue belongs to this repository or if it's more something for dotnet/core. Additionally I am also not 100% sure if I might have overlooked something and it would mean a lot to me if you could have a look at it.
Introduction
I am using .NET Core 2.1 with a Web API which is hosted on Azure as an App Service.
UserService : <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0" />
Service 1 : <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
The Service 1 is basically calling the UserService via a synchronous http call.
For my HttpClient I've implemented a very straight forward wrapper class which you can see here (only the relevant GET implementation):
Service 1
public async Task<T> GetAsync<T>(string relativeUri, string accessToken)
{
var result = default(T);
try
{
var httpRequestMessage = CreateHttpRequestMessage(HttpMethod.Get, relativeUri, accessToken);
// SendAsync is supposed to be thread safe
var response = await _httpClient.SendAsync(httpRequestMessage);
response.EnsureSuccessStatusCode();
// TODO : Only for debugging purposes
var content = await response.Content.ReadAsStringAsync();
_customHttpClientLogger.LogInformation(content);
using (var stream = await response.Content.ReadAsStreamAsync())
{
using (var reader = new JsonTextReader(new StreamReader(stream)))
{
result = _jsonSerializer.Deserialize<T>(reader);
_customHttpClientLogger.LogInformation("HTTP GET to {url} was successful.", relativeUri);
}
}
return result;
}
catch (Exception ex)
{
_customHttpClientLogger.LogError(ex, "HTTP GET to {url} received an error.", relativeUri);
throw;
}
}
private HttpRequestMessage CreateHttpRequestMessage(HttpMethod httpMethod, string relativeUri, string accessToken, string authenticationSchema = BEARER)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri(relativeUri, UriKind.Relative),
Method = httpMethod,
};
// Has to be added on a per-request basis, otherwise it would be shared with other requests.
request.Headers.Add("Authorization", $"{authenticationSchema} {accessToken}");
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Accept-Encoding", "gzip");
return request;
}
services.AddHttpClient<UserServiceHttpClient>()
.ConfigureHttpMessageHandlerBuilder(c => new HttpClientHandler()
{
UseProxy = false,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
})
.AddHttpMessageHandler<CorrelationIdDelegatingHandler>();
public class CorrelationIdDelegatingHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IOptions<CorrelationIdOptions> _options;
public CorrelationIdDelegatingHandler(
IHttpContextAccessor httpContextAccessor,
IOptions<CorrelationIdOptions> options)
{
_httpContextAccessor = httpContextAccessor;
_options = options;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (!request.Headers.Contains(_options.Value.Header))
{
request.Headers.Add(_options.Value.Header, _httpContextAccessor.HttpContext.TraceIdentifier);
}
return base.SendAsync(request, cancellationToken);
}
}
Service 2 (UserService)
[HttpGet("api/user")]
[MapToApiVersion("1.0")]
[Produces("application/json")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(List<User>), Description = "A list of user entities.")]
[SwaggerResponse((int)HttpStatusCode.InternalServerError, Description = "An error occured.")]
public async Task<IActionResult> GetAllAsync()
{
try
{
var users = await _userService.GetAllAsync();
return Ok(users);
}
catch (Exception ex)
{
_userControllerLogger.LogError(ex.InnerException ?? ex,
"An error occcured in the method {method}() in the class '{class}'.", nameof(GetAllAsync), nameof(UserController));
}
return StatusCode(StatusCodes.Status500InternalServerError);
}
Issue
Everything here works perfectly well on my localhost environment and the request is being processed by Service 1. Unfortunately, once I host this on Azure, the call to the api /api/user returns something like the following as HttpContent.
var content = await response.Content.ReadAsStringAsync();
_customHttpClientLogger.LogInformation(content);
? ?I?%&/m?{J?J??t??$?@??????iG#)?*??eVe]f@????{???{???;?N'????\fdl??J??!????~|?"????*f=?}?n??E???z??<[6?u?????O?j?U?v?>:/??v?v???????????[????????EV??Y?7?G???}??9}?i?:?[?????q????X?T3??????E{MIg??h?????O??_]L????>Z??yQ?g??^dm???IQ]??jgi?
The funny thing is, that if I call the UserService (/api/user) directly via Postman, then I do receive a proper json response. I also made sure that I use the exact same HttpHeaders as in the code.


Execution Paths
Localhost:
Postman => UserService (api/user) => (works) Postman => Service 1 => UserService (api/user) => (works) WebApplication => Service1 => UserService (api/user) => (works)
Azure:
Postman => UserService (api/user) => (works) Postman => Service 1 => UserService (api/user) => (doesnt work) WebApplication => Service1 => UserService (api/user) => (doesnt work)
Summary
No matter which execution path you take (also the one which dont work), the user service is always called and returns a successful response. I could verify via remote debugging that the user service was always returning a OK() response.
I am really struggeling to find out where the part with the encoding could have gone wrong.
The UserService in Azure seems to work without any troubles but as soon as I call it from Service 1 it seem to not work anymore.
Could it be that some HttpMessageHandler or Middleware is interfering with the request?
As strange as it sounds, this issue only appears once it's hosted in Azure.
Are there any Azure specific outbound rules or interceptors which could tamper with my request?
Here are the NuGet packages which I am using for Service 1:
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.6.0" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.PlatformAbstractions" Version="1.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" />
<PackageReference Include="Serilog" Version="2.7.1" />
<PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.2" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.1" PrivateAssets="All" />
I would be very grateful for everything which could point me in the right direction.
Thanks in advance!
Thanks for contacting us @HansMusterWhatElse. Would you be able to share a repro project as a GitHub repo?
Hi @mkArtakMSFT,
After hours of debugging I could finally manage to track it down - it's related to the fact that for some reason on Azure my gzipped response from the UserService isn't decompressed back.
I assume that for some reason the Accept-Encoding header is getting ignored.
I also found something related to Nginx which I hope doesn't apply to me.

If you have any ideas I am more than happy but otherwise I guess that you can close this issue.
Sorry @HansMusterWhatElse. No ideas really around this. As for Nginx, I don't think it's involved here in any way. Closing this as this is really external to this repo.