views:

29

answers:

2

I have implemented custom errors in my asp.net mvc application by following this article. What I have noticed is that if I go to http://www.mysite.com/some-non-existent-controller-and-action I get my 404 error page as expected. However, looking at what happens with firebug, I see that I get a 302 Found response for the non-existent page, which then redirects to my custom error page which then returns with a 404 (and displays the custom error page). Is this right? I don't think the 302 that is first returned is very good especially from an SEO perspective, and that maybe I need to think again about how I have implemented this.

A: 

Did you follow the advice down towards the bottom of the page adding a "catch-all" route that maps to your "NotFound" action:

routes.MapRoute("Catch All", "{*path}",
    new { controller = "Error", action = "NotFound" });

If you make this the very last route you add, any "unknown" URLs will map directly to your "NotFound" action on the ErrorController and you can just return the "not found" view directly from there, no redirects required.

Dean Harding
Yes I have this route.
s1mm0t
+1  A: 

The best guide(i think) for handling 404s can be found in this answer. Basically there are multiple ways in which 404s can happen:

  1. No route exists - matched by the catch all rule.
  2. Matched route but not found a controller - for rules with dynamic controller names - {controller}/{action}/{parameter} rule.
  3. Found route, but didn't find action - handled through HandleUnknownAction override.
  4. Found route and action but couldn't convert parameters - matched by the catch all rule.

The linked answer basically sets up a controller that can be executed from any point in the code without rewriting the URL - which is what you want.

In addition, you should also think about handling unhandled exceptions and bad URLs (like the ones containing unsafe characters like angle brackets). I that particular case you have to rewrite the URL, otherwise you can't render the response at all. These particular requests are kind of tricky, i blogged about that here.

Igor Zevaka
Thanks, this looks good. I will take a proper look and feedback
s1mm0t