Polly icon indicating copy to clipboard operation
Polly copied to clipboard

How to call HttpContext.SignOutAsync from StartUp.cs after waitandretry fails in .net core App

Open davecameos opened this issue 5 years ago • 2 comments

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.

davecameos avatar Nov 12 '20 11:11 davecameos

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?

martincostello avatar Nov 12 '20 12:11 martincostello

Thank you. I will try that and see if I can get it to work.

davecameos avatar Nov 12 '20 12:11 davecameos

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.

github-actions[bot] avatar Jul 06 '23 02:07 github-actions[bot]

This issue was closed because it has been inactive for 14 days since being marked as stale.

github-actions[bot] avatar Jul 21 '23 01:07 github-actions[bot]