使用 Polly 和 Typed Client 刷新令牌

kar*_*jan 5 polly asp.net-core

我有一个已在服务中配置的类型化客户端,我正在使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 7

您可以使用AddPolicyHandlerwhich 具有通过的重载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.
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

  • 向Polly调用同样的get服务不是自找麻烦吗?TypeClient.Get落入Polly,Polly然后调用TypedClient.Get,然后失败并再次落入Polly...... (2认同)