Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC showing error page on when sending responses with status 500

I have the following action in the server:

[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 not valid, it returns a JSON with the errors and the response has a 500 for the HTTP status code.

When deployed, instead of the JSON described, IIS is returning me this famed error page.

Here is the web.config with the detail for the customErrors section:

<customErrors mode="Off" defaultRedirect="~/error.htm">
    <error statusCode="404" redirect="~/errorhandling/pagenotfound" />
</customErrors>

I tried turning it to On but neither worked.

Where should I change to stop recieving that ugly error page instead of my beauty JSON?

Edit:

I changed the status code to 400, now I am getting the text Bad Request as a response, instead of the JSON:

Bad request text

like image 790
lante Avatar asked Dec 20 '22 08:12

lante


2 Answers

From this link:

Solved editing the web.config and adding the following attribute:

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

Another bizarre Microsoft story.

like image 155
lante Avatar answered Dec 24 '22 02:12

lante


You are using server error instead of client error. According to Wikipedia for 5XX errors:

"The server failed to fulfill an apparently valid request."

In this case your server works fine and the client send bad request. Use clients errors (4XX) instead.

like image 26
Sam FarajpourGhamari Avatar answered Dec 24 '22 01:12

Sam FarajpourGhamari