MVC : Set custom error pages - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

MVC : Set custom error pages

In this article I am going to explain how to set the custom error pages in asp.net MVC application.


Description:
It is very important to set the error pages in application to keep visitors browsing website. Mistake can happen when users browsing website. The most common errors are 404, 500 and 403.

Implementation:

HandleError attributes helps to handle the error in MVC application. There are 2 web.config files in application. Open the root folder web.config file and add the below given code in between <system.web>.

<customErrors mode="On" defaultRedirect="~/error/index">
      <error statusCode="404" redirect="~/error/NotFound"/>
    <error statusCode="500" redirect="~/error/Error500" />
    <error statusCode="403" redirect="~/error/Error403" />
    </customErrors>

Now add an empty controller to application and write the code as given below.

Controller code (ErrorController.cs):
public class ErrorController : Controller
    {
        //
        // GET: /Error/
        [HandleError]
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult NotFound()
        {
            return View();
        }
        public ActionResult Error500()
        {
            return View();
        }
        public ActionResult Error403()
        {
            return View();
        }
    }

Add the view for particular action result and show message that want to display.

View (Index):
@{
    ViewBag.Title = "Error";
}

<h2>OOPS something went wrong...</h2>
<a href="http://articlemirror.in">Go to Home Page</a>

View (Notfound ):-
@{
    ViewBag.Title = "NotFound";
}


<img src="~/images/404-Error-new.png" />

<a href="http://articlemirror.in">Go to Home Page</a>

Now build and run the application. Test it.
Hope this article helps you to configure error pages in your application.



What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon