简体   繁体   English

如何在全局范围内处理 httpclient 响应代码?

[英]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.据我所知,如果您在应用程序中收到来自 httpclient 的响应,它不会直接重定向到另一个页面。 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.通常情况下,我们可以先在 DateObsessedHandler 中抛出异常,然后我们可以使用 ExceptionHandler 中间件来处理异常并重定向到另一个页面。

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: Startup.cs 配置方法:

        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

       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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