Unable to add custom headers to HttpClient
See original GitHub issueMy application uses authenticated Web API endpoints using OAuth bearer tokens to retrieve images. I created a class AuthenticatedHttpClient which would add the Authorization header when contacting the endpoints.
public class AuthenticatedHttpClient : System.Net.Http.HttpClient
{
public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = await AccessTokenService.GetAccessToken();
if (token != null)
{
request.Headers.Remove("Authorization");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
return await base.SendAsync(request, cancellationToken);
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}
}
....
ImageService.Instance.Initialize(new FFImageLoading.Config.Configuration
{
HttpClient = new AuthenticatedHttpClient()
});
However, FFImageLoading never reaches SendAsync, I suspected that this override of SendAsync is never called, however I see that GetAsync(Uri, HttpCompletionOption, CancellationToken) is called, which calls SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken) which should call SendAsync(HttpRequestMessage, CancellationToken).
For some reason, my override of SendAsync is never called and I never get to inject my custom headers. However, if I omit the HttpCompletion parameter from DownloadAsync (DownloadCache.cs) or change it to HttpCompletionOption.ResponseContentRead, my overridden method gets called.
Is there another way to inject custom headers to get around this issue? One way for me to avoid the issue would be to call initialize every time my Access Token changes.
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (2 by maintainers)
Top GitHub Comments
I call ImageService.Instance.Initialize inside of MainActivitiy.onCreate before instantiating the forms app.
The System.Net.Http.HttpClientHandler has no GetAsync method. IMO, SendAsync should be correct, since I’m using the AuthenticatedHttpClientHandler for all other HttpClients to make requests to my webservice, which requires the access token in the header.
Hello, Could you help me with this? I need to add the “host” and userAgent on each request and I can’t get it works