我想向 500 Internal Server Error 页面添加标头
我正在使用 ASP.NET MVC,并且我的应用程序主要使用 JSON 查询工作。
如果服务器端出现问题,我会看到标准的“500 内部服务器错误”页面。这实际上很好。但我想在响应标头中添加一个字段:异常消息。
我的想法是在控制器中添加此覆盖:
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);
}
它起作用,但不是很简洁。有什么方法可以轻松做到这一点吗?谢谢!
I'm using ASP.NET MVC, and my application works mostly using JSON queries.
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.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在 web.config 中启用自定义错误:
这将呈现标准错误视图
~/Views/Shared/Error.aspx
并且您的自定义标头将附加到响应中。您也可以使用
filterContext.HttpContext.Response
而不是filterContext.RequestContext.HttpContext.Response
。它指向同一个对象,只是它更有意义一些。Try enabling custom errors in your web.config:
This will render the standard error view
~/Views/Shared/Error.aspx
and your custom header will be appended to the response.Also you could use
filterContext.HttpContext.Response
instead offilterContext.RequestContext.HttpContext.Response
. It points to the same object, it's just that it makes a little more sense.