views:

378

answers:

4

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?

A: 

Could just configure it through Web.Config like so:

<customErrors mode="RemoteOnly" defaultRedirect="[some url]" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="/errors/NotFound.aspx"/>
</customErrors>

Relevant bit of documentation

error
Optional element.
Specifies the custom error page for a given HTTP status code.
The error tag can appear multiple times. Each appearance defines one custom error condition.

R0MANARMY
+5  A: 

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>
Max Toro
A: 
  1. You're correct, create a NotFoundController and map route to it, say /404 and then put the URL in your web.config file (see @R0MANARMY) answer.

  2. You can just throw new HttpException(404, "Not Found") or if you don't want to throw exceptions (which is costly) you can simply set the status code to 404 via Response.StatusCode property and then return a View("My404Template") from your action methods.

chakrit
@chakrit: Won't asp.net mvc give you a 404 anyway without a NotFoundController? Or do you mean in case you want to redirect to something other than a static html 404 page?
R0MANARMY
+2  A: 

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.

Mendy
Simple and customizable, I like it.
Max Toro
don't forget about the unhandled events like bad urls. try this solution: http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095
cottsak
But this returns 200 status code, not 404.
Pavel Chuchuva
True, you have also to change the status code. But you get the point.
Mendy