我正在调用一个外部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
没有被调用-有人能帮我理解一下吗?我查看了Polly文档和Stack Overflow上的Polly问题,但我无法弄清楚发生了什么。
DoSomethingAsync
在哪里? - Zeeshan Badshah