【发布时间】:2022-01-07 07:57:46
【问题描述】:
我尝试在我的 Asp.net 核心 mvc 网页上实现一个全局错误处理程序。为此,我创建了一个错误处理程序中间件,如 this 博客文章中所述。
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
switch (error)
{
case KeyNotFoundException e:
// not found error
response.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
response.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);
context.Request.Path = $"/error/{response.StatusCode}"; // <----does not work!
}
}
}
中间件按预期工作并捕获错误。结果,我得到一个带有错误消息的白页。但我无法显示自定义错误页面。我用下面的代码行试过了。但这不起作用。
context.Request.Path = $"/error/{response.StatusCode}";
有什么想法可以实现我的目标吗?
提前致谢
【问题讨论】:
-
我认为您希望将响应重定向到
$"/error/{response.StatusCode}" -
没错,但我该怎么做呢? context.Response 没有路径属性。
-
试试
context.Response.Redirect($"/error/{response.StatusCode}") -
谢谢你的工作。但我也必须删除
await response.WriteAsync(result);行才能使其运行。 -
是的,当你重定向浏览器时,写响应是没有意义的。
标签: c# asp.net asp.net-core web asp.net-core-mvc