I'd like to add a header to the 500 Internal Server Error page
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开发者_JS百科 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!
Try enabling custom errors in your 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.
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.
精彩评论