我正在调用外部 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 问题,但我不知道发生了什么......