我有一个Web项目(C#,MVC5但没有WebAPI)和一个简单的HTTP REST客户端,它调用外部REST服务并获取accessToken etcing。
我想查看来自statusCode 401的所有Get / PostAsync调用的响应,但我发现在实现SendAsync
时我只能覆盖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
吗?
(我真正想要做的是刷新accessToken。)
答案 0 :(得分:6)
我认为你正走在正确的轨道上。您无需更改通话即可使用SendAsync
代替GetAsync
,PostAsync
等。相反,您需要更改实例化HttpClient
的方式:
var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher());
// GetAsync, PostAsync, etc will hit your handler
答案 1 :(得分:2)
使用装饰器或拦截器模式。
示例混凝土装饰者:
public class CustomDelegatingHandlerTokenRefresher() : DelegatingHandler
{
public CustomDelegatingHandlerTokenRefresher(DelegatingHandler handler)
{
InnerHandler = handler;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
RefreshToken();
return await InnerHandler.SendAsync(request, cancellationToken);
}
}