拦截C#HttpClient GetAsync [英] Intercept C# HttpClient GetAsync
问题描述
我有一个Web项目(C#,MVC5,但没有WebAPI)和一个简单的HTTP REST客户端,该客户端正在调用外部REST服务并获取accessToken等.
I have a web project (C#, MVC5 but no WebAPI) and a simple HTTP REST client that is calling an external REST service and acquires an accessToken etcing.
我想检查我所有对statusCode 401的Get/PostAsync调用的响应,但是我发现在实现DelegatingHandler
时只能覆盖SendAsync
方法.
I want to check the response from all my Get/PostAsync calls for statusCode 401 but I see that I can only override the SendAsync
method when implementing the DelegatingHandler
.
class CustomDelegatingHandler : DelegatingHandler
{
async protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
还有其他方法可以使我不更改所有异步调用的实现以使用SendAsync
吗?
Is there something else I can do so as not to change the implementation of all my async calls to use SendAsync
?
(我真正想做的是刷新accessToken.)
(What I really really want to do is refresh the accessToken.)
推荐答案
我认为您的做法正确.不过,您无需将调用更改为使用SendAsync
而不是GetAsync
,PostAsync
等.相反,您需要更改实例化HttpClient
的方式:
I think you're on the right track. You wouldn't need to change your calls to use SendAsync
instead of GetAsync
, PostAsync
, etc though. Rather, you'd need to change how you instantiate HttpClient
:
var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher());
// GetAsync, PostAsync, etc will hit your handler
这篇关于拦截C#HttpClient GetAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!