6

我有一个 Web 项目(C#、MVC5 但没有 WebAPI)和一个简单的 HTTP REST 客户端,它调用外部 REST 服务并获取 accessToken 等。

我想检查我的所有 Get/PostAsync 调用对 statusCode 401 的响应,但我发现我只能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。)

4

2 回答 2

8

我认为你在正确的轨道上。不过,您不需要将调用更改为 useSendAsync而不是GetAsync,PostAsync等。相反,您需要更改实例化方式HttpClient

var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher());
// GetAsync, PostAsync, etc will hit your handler
于 2015-03-17T21:32:13.377 回答
3

使用装饰器拦截器模式。

示例混凝土装饰器:

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);
    }
}
于 2015-03-17T18:17:44.450 回答