question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to add custom headers to HttpClient

See original GitHub issue

My 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:closed
  • Created 7 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
viktorgtcommented, Feb 12, 2017

I call ImageService.Instance.Initialize inside of MainActivitiy.onCreate before instantiating the forms app.

base.OnCreate(bundle);
CachedImageRenderer.Init();
ImageService.Instance.Initialize(new Configuration
{
    HttpClient = new HttpClient(new AuthenticatedHttpClientHandler()),
});
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new 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.

0reactions
cansado2930commented, Jun 21, 2020

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

C# Setting custom headers to httpclient gives error as ...
Internally the default HttpHeaders.Add will try to validate that you are adding a known HTTP header and will fail if not valid.
Read more >
Can't add custom HTTP headers · Issue #16151
I'm trying to add custom HTTP headers to my request like so: _client.DefaultRequestHeaders.TryAddWithoutValidation("app_id", _appIdProvider.
Read more >
Unable to add a custom user-agent header with HTTP Client
This is expected behavior. The HttpClient creates the User-Agent string as any "client application" (read: any web browser) would.
Read more >
Can't set custom header in httpclient (ionic 3 app angular 5)
I am trying to use an api which requires an API key 'Auth', I am trying to send the key using httpHeaders using...
Read more >
Custom Headers with HttpClient - The World According to Marc
The first thing you need to do is instantiate a new HttpRequestMessage object. You'll need to supply the HttpMethod (PUT, GET, etc.) and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found