Home > database >  HttpClient - Execute an async method before every call to SendAsync
HttpClient - Execute an async method before every call to SendAsync

Time:06-14

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(...)?

CodePudding user response:

I think that AOP, for Aspect Oriented Programming, could interest you for your kind of problems.

The point of this paradigm is to increase the modularity of your code by separating the different sections and defining rules called pointcut to execute one or many specific functions before, after, when it calls an exception, etc.

In your case, you could define a Pointcut that execute your async method on entry (on the startup of the function but before any code is called) of SendAsync.

To do so, there are many AOP framework existing in C#. I know PostSharp is a good framework for AOP but I encourage you to try many of them to find which one fit the most for your needs.

Here is the link to PostSharp : https://www.postsharp.net/

I hope my answer could help you. Have a good day.

CodePudding user response:

@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.

  • Related