Sunday, April 3, 2011

404–This is not the web page you are looking for

On a given website, not all users will type the right link, and your ASP.NET MVC pages will have the exact controller action to render a given view.  In such cases, you need a nice 404 page.  You can go as fancy as github’s 404.  Check this out.

github_404

You can achieve this and similar other errors tapping into the Application_Error handler in your Global.asax file:

1 protected void Application_Error(object sender, EventArgs e)
2 {
3 var app = (MvcApplication)sender;
4 var context = app.Context;
5 var ex = app.Server.GetLastError();
6 context.Response.Clear();
7 context.ClearError();
8 var httpException = ex as HttpException;
9
10 var routeData = new RouteData();
11 routeData.Values["controller"] = "Error";
12 routeData.Values["exception"] = ex;
13 routeData.Values["action"] = "http500";
14 if (httpException != null)
15 {
16 switch (httpException.GetHttpCode())
17 {
18 case 404:
19 routeData.Values["action"] = "http404";
20 break;
21 // implement other http statuses here as well.
22 }
23 }
24 IController controller = new ErrorController();
25 controller.Execute(new RequestContext(new HttpContextWrapper(context),
26 routeData));
27 }


Then add an ErrorController.cs file and implement the below:


1 namespace Http404NotFound.Controllers
2 {
3 public class ErrorController : Controller
4 {
5 public ActionResult Http404()
6 {
7 return View();
8 }
9
10 // implementation of other status can go here...
11 }
12 }

Using the new Razor syntax and file format, The Http404.cshtml can look like this:


1 @{
2 ViewBag.Title = "Http404";
3 }
4
5 <h2>Http404</h2>
6 <img src="../../Content/images/github_404.PNG" />
7
8

You can find more MVC Cook book recipes in ASP.NET MVC 2 Cookbook.


Happy Coding!