【问题标题】:I'd like to add a header to the 500 Internal Server Error page我想在 500 Internal Server Error 页面中添加一个标题
【发布时间】:2011-06-09 00:39:10
【问题描述】:

我正在使用 ASP.NET MVC,我的应用程序主要使用 JSON 查询。

如果服务器端出现问题,我会看到标准的“500 Internal Server Error”页面。这其实很好。但我想在响应标头中再添加一个字段:异常消息。

我的想法是在控制器中添加这个覆盖:

protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
        filterContext.RequestContext.HttpContext.Response.AppendHeader("Exception", filterContext.Exception.Message);
        filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }

很遗憾,我没有在响应标头中获得新字段。

但是,如果在我的控制器的方法上执行此操作,它会起作用:

try
{
}
catch (Exception ex)
{
    Response.Headers.Add("Exception", ex.Message);
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    return Content(ex.Message);
}

它有效,但不是很整洁。有没有办法可以轻松做到这一点?谢谢!

【问题讨论】:

    标签: .net asp.net-mvc json asp.net-mvc-2 http-headers


    【解决方案1】:

    尝试在您的 web.config 中启用自定义错误:

    <system.web>
        <customErrors mode="On" />
    </system.web>
    

    这将呈现标准错误视图~/Views/Shared/Error.aspx,并且您的自定义标头将附加到响应中。

    您也可以使用filterContext.HttpContext.Response 代替filterContext.RequestContext.HttpContext.Response。它指向同一个对象,只是它更有意义。

    【讨论】:

    • 这很烦人,但似乎我总是得到 IIS 错误页面,无论我在 web.config 或代码中做什么。即使是标准的 ASP.NET MVC 示例也没有给我自定义错误页面(我也使用 CustomErrors On there...)
    • @TigrouMeow,你的控制器是用[HandleError] 属性装饰的吗?
    • 是的,但它不会改变任何东西。
    • 哪里抛出异常?
    • 在控制器的方法中。我刚刚编辑了我的问题,找到了一种可行的方法,但这并不理想。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2012-01-31
    • 2020-06-24
    • 1970-01-01
    • 2015-08-16
    • 2022-12-08
    • 1970-01-01
    相关资源
    最近更新 更多