Search code examples
c#asp.net-coredotnet-httpclientasp.net-core-identityihttpclientfactory

HttpClient - Execute an async method before every call to SendAsync


I'm in an ASP.Net Core environment and want my classes to use a named HttpClient which they retrieve from an IHttpClientFactory. They need to add a Bearer token into the Authorization header. In order to do that, they need to make an async call which will either get the token from an OAuth endpoint, or retrieve it from the cache.

I know there are calls for services.AddHttpClient(...) which I can use to modify the HttpClient instances which are retrieved from the IHttpClientFactory. However that only allows for sync methods (It is an Action<ServiceProvider, HttpClient>), because IHttpClientFactory.GetClient(string name) is sync too.

Is there anything built into that I can use to make that async call and add the header either when retrieving the client, or when making the request by calling SendAsync(...)?


Solution

  • @alexei-levenkov pointed me in the right direction in the comments. DelegatingHandler is the way to solve this problem.

    Actually I'm using Microsoft.Identity.Web which comes with its own AddMicrosoftIdentityAppAuthenticationHandler() which will automatically insert the handler, I was looking for.