gpt4 book ai didi

asp.net-core - 使用Polly和Typed Client刷新 token

转载 作者:行者123 更新时间:2023-12-03 16:03:41 27 4
gpt4 key购买 nike

我有一个已在服务中配置的Typed Client,并且我正在使用Polly进行临时故障的重试。

目的:我想利用Polly实现刷新 token ,只要目标站点发出401响应,我都希望Polly刷新 token 并再次继续初始请求。

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

onRetry中的“上下文”为将任何对象添加到字典中提供了一些支持,但是我无法访问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.
});
});
});

关于asp.net-core - 使用Polly和Typed Client刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com