我处于ASP.NET核心环境中,希望我的类使用他们从 ihttpclientfactory
中检索的名称 httpclient
。
他们需要在授权标题中添加一个载体令牌。为了做到这一点,他们需要进行异步调用,该调用将从OAuth端点获取令牌,或从缓存中检索它。
我知道有 services.addhttpclient(...)
的电话,我可以用来修改 httpclient
实例,这些实例是从 ihttpclientfactory
。但是,这仅允许同步方法(这是 Action< serviceProvider,httpclient>
),因为 ihttpclientfactory.getClient(string name)
也是同步的。
我可以使用任何内置的内置,可以在检索客户端时或通过调用 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(...)
?
发布评论
评论(3)
我认为,对于面向方面的编程,AOP可能会让您感兴趣。
该范式的重点是通过将不同的部分和称为PointCut的规则分开来增加代码的模块,以执行一个或多个特定函数,此前,之后,之后,称为异常等。
在您的情况下,您可以定义一个
sendAsync
在输入时执行您的异步方法(在函数的启动但在调用任何代码之前)。为此,C#中存在许多AOP框架。我知道PostSharp是AOP的好框架,但我鼓励您尝试许多人找到最适合您需求的框架。
这是PostSharp的链接: https://www.postsharp.net/
我希望我的答案能有所帮助你。
祝你有美好的一天。
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.
@Alexei-Levenkov在评论中指出了正确的方向。
是解决此问题的方法。
实际上,我正在使用
microsoft.Identity.web
,它带有其自己的addmicrosoftitypapauthenticationhandichichander()
,它将自动插入处理程序,我正在寻找。@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 ownAddMicrosoftIdentityAppAuthenticationHandler()
which will automatically insert the handler, I was looking for.如果您只想将其用于
sendAsync
方法,则可以通过继承httpclient
这样很简单:if you just want to use it for
SendAsync
method it would be simple by inheritingHttpClient
like this: