lante
lante

Reputation: 7336

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

Upvotes: 4

Views: 1835

Answers (3)

Łukasƨ Fronczyk
Łukasƨ Fronczyk

Reputation: 457

Here's what to do if you need to use both Custom Error Pages and sometimes return custom data for http statuses defined in httpErrors section: - set existingResponse="Auto" in web.config (httpErrors section, that's where you define Custom Error Pages); - set TrySkipIisCustomErrors = true in your action (one that returns 4xx status and a content); - clear server error in global.asax (in Application_Error() - Server.ClearError()) and re-set the status code (Reponse.StatusCode = ((HttpException)Server.GetLastError()).GetHttpCode())

Upvotes: 1

lante
lante

Reputation: 7336

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.

Upvotes: 8

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

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.

Upvotes: 2

Related Questions