Wednesday, December 24, 2014

How to handle page not found exception in MVC?

There are many way to handle page not found exception. Here is I am describing a simple way to handle this. It just captures the http error status code 404 and redirects the user to Page not found view.
Create a simple view to show page not found message. I suggest to create this “PageNotFound.cshtml” view in the shared folder. See the below code of the view.

<div class="row-fluid visible-on" style="padding-top:70px;">
    <div class="col-lg-3 col-md-3 col-sm-3"></div>
    <div class="col-lg-6 col-md-6 col-sm-6">       
        <div class="well">
            <h4>
                Page Not Found
            </h4><hr />
            <p>
                The requested page does not exist.<br /><br />

Please try correct URL or @Html.ActionLink("click here""Login""Account", routeValues: null, htmlAttributes: new { id = "loginLink" }) to go to login screen.
            </p>
        </div>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 visible-lg"></div>
</div>

We need to change the web.config file to redirect the control to ErrorController in case of exception where the response status code is 404.

Here is the code to add in web.config file.

 <customErrors mode="On">     
      <error statusCode="404" redirect="Error/PageNotFound"/>
</customErrors>

Let’s go through the final step to complete the exception handling. We need to create a controller with name “ErrorController” and add “PageNotFound” action inside the controller class. Here is the full code snippet.

public class ErrorController : Controller
    {
        //Redirect to Page not found page in case of 404 http status code.
        // GET: PageNotFound
        public ActionResult PageNotFound()
        {
            Response.StatusCode = 404;
            return View("PageNotFound");
        }
    }


 That’s it. Is not it easy? Now if someone tries to enter wrong URL inside of showing default browser page not found page. It will redirect to the custom view we have created. This is the simplest way to hand page not found exception. If you want to implement a sophisticated exception handing code then please refer the below links for few good references. 

No comments:

Post a Comment