0

I have setup Custom Errors for my site as my Web.config shows below:

<system.web>
    <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error/Error400">
      <error statusCode="400" redirect="~/Error/Error404"/>
      <error statusCode="404" redirect="~/Error/Error404" />
      <error statusCode="403" redirect="~/Error/Error403" />
      <error statusCode="500" redirect="~/Error/Error500" />
    </customErrors>   
</system.web>

And also

<system.webServer>  
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="400" />
        <error statusCode="400" path="/Error/Error400" responseMode="ExecuteURL" />
        <remove statusCode="403" />
        <error statusCode="403" path="/Error/Error403" responseMode="ExecuteURL" />
        <remove statusCode="404" />
        <error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />      
        <remove statusCode="500" />
        <error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

I am throwing errors like this from my controllers:

throw new HttpException((int)HttpStatusCode.BadRequest, "The checklist Id is not specified. EntityId: " + this.LoggedInEntity.EntityId + "; userId: " + this.LoggedInUser.UserId);

The Error controller that handles the custom error page requests is:

public class ErrorController : Controller
{
    public ActionResult Error400()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return View(error);
    }

    public ActionResult Error403()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.Forbidden;
        return View(error);
    }

    public ActionResult Error404()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View(error);
    }

    public ActionResult Error500()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View(error);
    }
}

However, in the example thrown exception which is a 400 Error, the 400 action doesn't get called. Instead, the 500 action gets called. How can I make it call the correct 400 action instead for the thrown error?

I am using ELMAH for my error logging and it is showing the correct error code: Elmah log

Rhys Stephens
  • 889
  • 3
  • 20
  • 36

1 Answers1

1

According to the following answer, ResponseRewrite won't work with MVC routes:

https://stackoverflow.com/a/3770265/758765

If you read through Bens (awesome) blog post, he's using actual files to represent the 404 and 500 responses and not an MVC controller.

Community
  • 1
  • 1
ThomasArdal
  • 4,999
  • 4
  • 33
  • 73