articles

Home / DeveloperSection / Articles / Custom Error Page in Asp.Net Mvc 4

Custom Error Page in Asp.Net Mvc 4

Custom Error Page in Asp.Net Mvc 4

Sumit Kesarwani 8339 20-Sep-2014

Here In this article, I’m explaining how to create a custom error page and invoke it when an error comes in the application using asp.net MVC 4.

Step 1

Create an empty asp.net MVC 4 project and add a controller named “HomeController” like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace CustomErrorPageMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
           return View();
        }
 
    }
}

 Step 2

Now add a view to the project named “Index”

@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>

 Step 3

Now add a new folder to the project named “Shared” like this:

Custom Error Page in Asp.Net Mvc 4

 And add a view named “Error” like this:

@{
    Layout = null;
}
 
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error</title>
</head>
<body>
    <hgroup>
        <h1>Error.</h1>
        <h2>An error occurred while processing your request.</h2>
    </hgroup>
</body>
</html>
Step 4

Now add customErrors mode=” On” in the web.config file like this:

Custom Error Page in Asp.Net Mvc 4

 Step 5

Now add these codes in the HomeController like this:

  [HandleError()]
  public ActionResult Index()
  {
      string temp = Session["temp"].ToString();
      return View();
  }
Output

Now run the application:

Custom Error Page in Asp.Net Mvc 4

The above will come and now press F5 and your custom error page will show:

Custom Error Page in Asp.Net Mvc 4


Updated 14-Feb-2020

Leave Comment

Comments

Liked By