Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 Pages in ASP.NET MVC

I'm building my first ASP.NET MVC website, and I'm trying to figure out how to implement a 404 page.

Should I create a controller called "404Controller?" If so, how do I then register this Controller with IIS so that it redirects 404s to that page? Also, in a situation where something is not found (in the database, for example) by some other Controller code, how would I redirect the request to my 404 page?

like image 235
Maxim Zaslavsky Avatar asked Apr 04 '10 05:04

Maxim Zaslavsky


People also ask

How does MVC handle custom errors in asp net?

You can use the <customErrors> in web. config to display custom pages when exceptions occurred in MVC application with the response status code 200. For SEO reason, you may want to display a custom error page and return an appropriate error code in ASP.NET webform or MVC application.

What do you mean by 404 in asp net?

Best web development and SEO practices dictate that any webpage which does not exist, return an HTTP response code of 404, or Not Found. Basically, this response code means that the URL that you're requesting does not exist.


2 Answers

There's no single answer for what your are trying to do, the simplest and what I like is using the HttpException class, e.g.

public ActionResult ProductDetails(int id) {

   Product p = this.repository.GetProductById(id);

   if (p == null) {
      throw new HttpException(404, "Not Found");
   }

   return View(p);
}

On web.config you can configure customError pages, e.g.

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
   <error statusCode="404" redirect="Views/Errors/Http404.aspx" />
</customErrors>
like image 160
Max Toro Avatar answered Sep 30 '22 16:09

Max Toro


The favorite option for me is to return a view called 404.

if (article == null)
    return View("404");

This will let you the option to have a generic 404 view in the shared folder, and a specific 404 view to the article controller.

In addition, a big plus is that there is no redirect over here.

like image 21
Fitzchak Yitzchaki Avatar answered Sep 30 '22 16:09

Fitzchak Yitzchaki