【问题标题】:Global Error Handling in ASP.NET Core MVCASP.NET Core MVC 中的全局错误处理
【发布时间】: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


【解决方案1】:

您似乎希望将浏览器重定向到错误页面。

为此,您需要替换:

context.Request.Path = $"/error/{response.StatusCode}";

context.Reponse.Redirect($"/error/{response.StatusCode}");

另外,由于您要发送重定向,因此响应内容需要为空,因此也请删除 response.WriteAsync 位。

var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多