簡體   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;
    }

我試過上面的委托處理程序。 如何重定向到控制器操作?

據我所知,如果您在應用程序中收到來自 httpclient 的響應,它不會直接重定向到另一個頁面。 您仍然需要編寫一些代碼來處理響應並從您的應用程序返回一個新的上下文。

通常情況下,我們可以先在 DateObsessedHandler 中拋出異常,然后我們可以使用 ExceptionHandler 中間件來處理異常並重定向到另一個頁面。

更多細節,您可以參考以下代碼:

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

        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