ASP.NET MVC showing error page when submitting responses with 500 status
The server has the following action:
[HttpPost]
public JsonResult SearchContracts(SearchViewModel vm)
{
List<string> errors;
if (IsValid(vm, out errors))
{
return Json(service.Search(vm), JsonRequestBehavior.AllowGet);
}
else
{
HttpContext.Response.StatusCode = 500;
return Json(new { Errors = errors }, JsonRequestBehavior.AllowGet);
}
}
Locally, it works great. When the request is invalid, it returns JSON with errors and the response has an 500
HTTP status code.
When deployed, instead of the described JSON, IIS returns me this famous error page .
Here is web.config
the detail for the section customErrors
:
<customErrors mode="Off" defaultRedirect="~/error.htm">
<error statusCode="404" redirect="~/errorhandling/pagenotfound" />
</customErrors>
I tried to turn it into On
but didn't work.
Where should I change to stop getting this ugly error page instead of my beauty JSON?
Edit:
I changed the status code to 400
, now I am getting text Bad Request
as response, not JSON:
source to share
Here's what to do if you need to use both custom error pages and sometimes return custom data for http statuses defined in the httpErrors section: - set existingResponse="Auto"
in web.config (httpErrors section where you specify custom error pages); - set TrySkipIisCustomErrors = true
in your action (which returns 4xx status and content); - clear server error in global.asax (in Application_Error()
- Server.ClearError()
) and re-set status code ( Reponse.StatusCode = ((HttpException)Server.GetLastError()).GetHttpCode()
)
source to share