我想在500内部服务器错误页面中添加一个标题。

时间:2022-10-19 17:55:22

I'm using ASP.NET MVC, and my application works mostly using JSON queries.

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

If something goes wrong on the server-side, I get the standard "500 Internal Server Error" page. That's actually fine. But I'd like to add one more field in the response headers : the Exception's Message.

如果服务器端出现问题,我将获得标准的“500内部服务器错误”页面。这实际上是很好。但是我想在响应头中添加一个字段:异常的消息。

My idea was to add this override in the controller :

我的想法是在控制器中添加这个重载:

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

Unfortunately, I don't get the new field in the response headers.

不幸的是,我在响应头中没有得到新的字段。

However, if do this on my controller's methods, it works:

但是,如果在我的控制器的方法上这样做,它可以工作:

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

It works, but it's not very neat. Is there a way I can do this easily? Thanks!

它可以工作,但不是很整洁。有没有一种方法我可以很容易地做到这一点?谢谢!

1 个解决方案

#1


1  

Try enabling custom errors in your web.config:

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

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

This will render the standard error view ~/Views/Shared/Error.aspx and your custom header will be appended to the response.

这将呈现标准错误视图~/视图/共享/错误。aspx和您的自定义标头将被附加到响应。

Also you could use filterContext.HttpContext.Response instead of filterContext.RequestContext.HttpContext.Response. It points to the same object, it's just that it makes a little more sense.

还可以使用filterContext.HttpContext。而不是filterContext.RequestContext.HttpContext.Response响应。它指向同一个物体,只是它更有意义。

#1


1  

Try enabling custom errors in your web.config:

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

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

This will render the standard error view ~/Views/Shared/Error.aspx and your custom header will be appended to the response.

这将呈现标准错误视图~/视图/共享/错误。aspx和您的自定义标头将被附加到响应。

Also you could use filterContext.HttpContext.Response instead of filterContext.RequestContext.HttpContext.Response. It points to the same object, it's just that it makes a little more sense.

还可以使用filterContext.HttpContext。而不是filterContext.RequestContext.HttpContext.Response响应。它指向同一个物体,只是它更有意义。