拦截C#HttpClient GetAsync

时间:2015-03-17 18:10:37

标签: c# httpclient sendasync

我有一个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。)

2 个答案:

答案 0 :(得分:6)

我认为你正走在正确的轨道上。您无需更改通话即可使用SendAsync代替GetAsyncPostAsync等。相反,您需要更改实例化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);
    }
}