简体   繁体   中英

How can I handle httpclient response code globally?

public class DateObsessedHandler : DelegatingHandler
{          
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        var requestDate = request.Headers.Date;
        // do something with the date ...
         
        var response =  await base.SendAsync(request, cancellationToken);
 
       // if(response.statuscode is 403) 
       // How do I redirect?
 
        return response;
    }

I've tried the delegation handler above. How do I redirect to a controller Action?

As far as I know, if you get the response from httpclient in your application, it will not directly redirect to another page. You still need write some codes to handle the response and return a new context from your application.

Normally, we could firstly throw the exception in the DateObsessedHandler and then we could use ExceptionHandler middleware to handle the exception and redirect to another page.

More details, you could refer to below codes:

    public class DateObsessedHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var requestDate = request.Headers.Date;
            // do something with the date ...

            var response = await base.SendAsync(request, cancellationToken);

            if (response.StatusCode == HttpStatusCode.Forbidden)
            {

                throw new Exception("403");
            }

            // if(response.statuscode is 403) 
            // How do I redirect?

            return response;
        }
    }

Startup.cs Configure method:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env){

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    var exceptionHandlerPathFeature =
                       context.Features.Get<IExceptionHandlerPathFeature>();

                    if (exceptionHandlerPathFeature?.Error.InnerException.Message == "403")
                    {
                        context.Response.Redirect("http://www.google.com");

                    }


                });
            });
          // other middleware

       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM