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:

Bad request text

+3


source to share


3 answers


From this link :

Fixed editing web.config

and adding the following attribute:



<system.webServer>
    ...
    <httpErrors existingResponse="PassThrough"></httpErrors>
    ...
</system.webServer>

      

Another strange Microsoft story.

+7


source


Server error is used instead of client error. According to Wikipedia for 5XX errors:

"The server did not fulfill an explicitly valid request."



In this case, your server is working fine and the client is sending the wrong request. Use client errors (4XX) instead.

+2


source


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()

)

0


source







All Articles