Polly RetryAsync 不工作并且代码未记录

Polly RetryAsync not working and code is not logged

我正在尝试使用 AsyncRetryPolicy 处理所有 401 响应。

一些注意事项:

重试政策如下:

var unauthorizedPolicy = Policy.Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.Unauthorized)
    .RetryAsync(3, async (exception, retryCount) =>
    {
        Logger.Instance.Info($"Unauthorized, token probably expired, retry count: {retryCount}");
        try
        {
            Logger.Instance.Error(exception.Message);
            Logger.Instance.Info("Retrying request and retrive refresh token");
            var token = await _authService.SignInSilentlyAsync();
            await SecureStorage.SetAsync(Constants.PreferencesNames.Token.Value, token);
        }
        catch (Exception ex)
        {
            Logger.Instance.Error(ex.Message);
            Logger.Instance.Info("SignInSilentlyAsync failed, going to login page");
            NavigationService.ReplaceRoot(new LoginPageViewModel());
        }
    });

这是在另一个class中执行的:

result = await _taskManager._defaultPolicyForHttpRequests // the above defined unauthorizedPolicy
    .ExecuteAndCaptureAsync<T>(async () => await task)
    .ConfigureAwait(false);

基本上,当令牌过期时,我尝试并成功获得一个新令牌,但似乎每次尝试仍然使用旧令牌:

从日志中可以看出,令牌已成功检索,但我认为重试调用时使用的是旧令牌。我不能确定,因为通话不再记录。

这引出了我的第二个问题,有没有什么方法可以 logdebug Polly 重试的每个 HTTP 调用?

As you can see from the logs, the token is successfully retrieved, yet I think the old one is used when retrying the call. I cannot be sure because the call is no longer logged.

代码只有一个调用:

var task = SomeMethodNotShownAsync();
result = await _taskManager._defaultPolicyForHttpRequests // the above defined unauthorizedPolicy
    .ExecuteAndCaptureAsync<T>(async () => await task)
    .ConfigureAwait(false);

特别是,这是有问题的部分:

ExecuteAndCaptureAsync<T>(async () => await task)

await 不是 "execute a task"。它异步等待任务完成。所以 Polly 第一次执行 async () => await task 时,它会异步等待任务完成。它最终以错误完成。 async () => await task 的所有未来执行异步等待 相同的任务 完成 - 该任务 已经完成 但有错误。

所以当前代码让 Polly 重试 "wait for the operation to complete"。它不会重试操作本身。

要解决此问题,让 Polly 每次都重试实际工作,而不是只重试 "wait for the operation to complete":

result = await _taskManager._defaultPolicyForHttpRequests // the above defined unauthorizedPolicy
    .ExecuteAndCaptureAsync<T>(async () => await SomeMethodNotShownAsync())
    .ConfigureAwait(false);

is there any way to log and debug each HTTP call that Polly retries?

已经是了。 :) 只有一次调用的日志消息的原因是 只有一次调用。