我正在调用外部 API,并希望处理调用返回
Unauthorized
HttpResponseMessage
的事件。发生这种情况时,我想刷新访问令牌并再次拨打电话。
我正在尝试将
Polly
与以下代码一起使用:
public async Task<HttpResponseMessage> MakeGetRequestAsync()
{
var retryPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.Retry(1, (exception, retryCount) =>
{
RefreshAccessToken();
});
var result = await retryPolicy.ExecuteAsync(() => CallApiAsync());
return result;
}
private async Task<HttpResponseMessage> CallApiAsync()
{
var url = Options.ResourceSandboxUrl;
var httpClient = new HttpClient();
SetRequestHeaders(httpClient);
var response = await httpClient.GetAsync(url);
response.StatusCode = HttpStatusCode.Unauthorized;
return response;
}
我在
语句和ExecuteAsync
中放置了断点 - 当我跨过DoSomethingAsync
时,不会调用ExecuteAsync
,控制权返回到调用DoSomethingAsync
的函数MakeGetRequestAsync
我不明白为什么不调用
DoSomethingAsync
- 任何人都可以帮助我实现我想要实现的目标吗?
我查看了 Stack Overflow 上的 Polly 文档和 Polly 问题,但我不知道发生了什么..
。特别是这是建议的代码片段:
var authorisationEnsuringPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(
retryCount: 1, // Consider how many retries. If auth lapses and you have valid credentials, one should be enough; too many tries can cause some auth systems to blacklist.
onRetryAsync: async (outcome, retryNumber, context) => FooRefreshAuthorizationAsync(context),
/* more configuration */);
var response = authorisationEnsuringPolicy.ExecuteAsync(context => DoSomethingThatRequiresAuthorization(context), cancellationToken);
FooRefreshAuthorizationAsync(...)
方法可以获取新的授权令牌,并将其传递给使用
通过策略执行的委托。Polly.Context
await
时,会发生两件事