How to call HttpContext.SignOutAsync from StartUp.cs after waitandretry fails in .net core App
Summary: What are you wanting to achieve?
I would like to sign out the user if the wait and retry fails. How can I call HttpContext.SignOutAsync that is in a method in a controller, when the last attempt fails? This is the code I have got so far:
Startup.cs
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
var jittered = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(6), retryCount: 3);
return HttpPolicyExtensions
.HandleTransientHttpError()
// Handle 404 not found
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
// Handle 401 Unauthorized
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.Unauthorized)
// Handle Network failures, HTTP 5XX status codes (server errors) and HTTP 408 status code (request timeout)
.WaitAndRetryAsync(jittered, onRetry: (exception, calculatedWaitDuration) => {
// exception handler
//Debug.WriteLine("Policy Logging: {0}", exception.Exception.Message);
**// TODO SIGN OUT CURRENT SESSION**
});
}
public void ConfigureServices(IServiceCollection services)
{
// code abbreviated for simplicity
services.AddHttpClient<TSClient>("TSHttpClient",
x => { x.BaseAddress = new Uri(Configuration["TSAPIConfiguration:BaseAddress"]); }
).AddPolicyHandler(GetRetryPolicy());
}
This works well. It tries for a number of times to execute the code and if it fails, it throws the exception. I would like to sign out the current user to force them to log in again.
I have this method to log out when clicking on a log out button. How can I call this from GetRetryPolicy() in startup? Is there an easier way?
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties
{
RedirectUri = Url.Action("Index","Home")
});
}
Thank you.
Maybe it would be easier to catch the exception thrown by Polly when the retries all fail, and then do the sign-out from the catch clause? Then the Polly setup doesn't need access to the HttpContext or to make any extended business logic decisions?
Thank you. I will try that and see if I can get it to work.
This issue is stale because it has been open for 60 days with no activity. It will be automatically closed in 14 days if no further updates are made.
This issue was closed because it has been inactive for 14 days since being marked as stale.