I'm using Polly and IHttpClientFactory
to handle my fault tolerance, which is working fine for retry and circuit breaker in .NET Core 3.1
I'm not trying to handle any 401's, which I can do within the controller, but I can't find a way to refresh the token from the StartUp
This is my policy in startup
IAsyncPolicy<HttpResponseMessage> httpWaitAndRetryPolicy =
Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(3, sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(retryAttempt),
onRetry: (httpResponseMessage, span, retryCount, ctx) =>
{
if (httpResponseMessage.Result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
PerformReauthorazation();
}
Console.WriteLine($"Retrying({retryCount})...");
});
private void PerformReauthorazation()
{
var x = 0;
//do something
}
But this is detached from from the actual controller as you would expect.
To reauthorise I need to call and get a new token to an end-point with all the credentials.
Then I add the following header
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken.AccessToken);
But how do I do this from the StartUp?