[英]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.