使用带类型客户端的 Polly 刷新令牌

Refresh Token using Polly with Typed Client

我有一个已在服务中配置的类型化客户端,我正在使用 Polly 重试瞬时故障。

目的:我想利用Polly实现刷新令牌,每当目标站点有401响应时,我希望Polly刷新令牌并再次继续初始请求。

问题是有类型的客户端有所有的api方法和刷新令牌方法,当从有类型的客户端发起请求时,我如何再次访问有类型的客户端以调用刷新令牌并继续初始请求?

onRetry 中的 'Context' 提供了一些支持,可以将任何对象添加到字典中,但我无法访问 SetPolicyExecutionContext('someContext') 方法,我不想在所有对象上添加它启动调用之前的方法,因为有很多 API.

// In Service Configuration

// Refresh token policy

var refreshTokenPolicy = Polly.Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(1, (response, retrycount, context)) =>
{
    if(response.Result.StatusCode == HttpStatusCode.Unauthorized)
    {
         // Perform refresh token
    }
}

// Typed Client 
services.AddHttpClient<TypedClient>();

public class TypedClient
{
    private static HttpClient _client;
    public TypedClient(HttpClient client)
    {
        _client = client;
    }

    public string ActualCall()
    {
        // some action
    }

    public string RefreshToken()
    {
        // Refresh the token and return
    }
}

您可以使用AddPolicyHandler,它的重载通过IServiceProvider。所以你需要做的就是:

services.AddHttpClient<TypedClient>()
    .AddPolicyHandler((provider, request) =>
    {
        return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
            .RetryAsync(1, (response, retryCount, context) =>
            {
                var client = provider.GetRequiredService<TypedClient>();
                // refresh auth token.
            });
        });
    });