asp.net mvc Bad Request

Posted on

Question :

When using the HttpStatusCodeResult class as a return to a Action , how do I redirect the user to a custom page based on the error?

    

Answer :

Set the pages to be returned for each error code in your web.config file.

<configuration>
  <system.web>
    <customErrors mode="On" redirectMode="ResponseRewrite">
        <error code="404" path="404.html" />
        <error code="500" path="500.html" />
    </customErrors>
  </system.web>
</configuration>

Entries do not need to be static. They can even be returned by Views of specific .

The redirectMode makes the answer really the desired code. The default redirection problem is that the redirect causes the redirect page to return with code 200 (OK), which is wrong.

    

There are several ways to do this, you can in the action itself identify the error and redirect, you can also use global.asx but I recommend you use web.config for this.

<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="400" redirect="~/400"/>
        </customErrors>
    </system.web>
</configuration>

Create the route, controller, and view for the error page you want to view.

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" }
);

Controller

public ActionResult HttpStatus404()
{
    return View();
}

Source: link

    

Leave a Reply

Your email address will not be published. Required fields are marked *