views:

64

answers:

2

Is there any way to catch a "controller not found" event from the framework? Maybe this event doesn't exist. But if I just pick a URL to throw at the routing system of the framework like:

http://localhost:54321/foobar

The final result without modification is a 404 error.

Is the easiest way to catch this through a custom ControllerFactory? Then handle it from there.

UPDATE: I'm looking for a way to catch and handle earlier in the request flow. Not at the controller level. See comments to Jon Galloway's answer.

+1  A: 

I'd add a catchall route at the end of your route declarations and handle it there.

/* all your other routes here */
routes.MapRoute("NotHandled", 
  "{*url}",
  new { controller = "NotFound", action = "Index" });
Jon Galloway
Is that "NotHandled" a magic string that is recognized by the framework?
Robert Harvey
No. That's just a name. The "magic" is that it's a catchall URL that hasn't been caught by anything else.
James S
Right, you could name it "Monkey" if you wated. The {*yournamehere} route will match anything. That's why it's important to list it last, or it will prevent your other routes from matching.
Jon Galloway
Jon - then I would still have to have a hard-coded Controller. I'm looking for more control than that. Like the ability to kick up a Microsoft.Scripting.Hosting.ScriptEngine to handle the request. Thoughts?
tyndall
Is a custom ControllerFactory then the best way to extend the MVC code without altering it?
tyndall
+1  A: 

I think there are more issues here than meets the eye.

In particular, what happens when a user invokes a valid action on a valid controller, and the requested resource — product, article, sub-category etc — doesn’t exist?

Also, for search engine purposes, the invalid URL needs to return a true 404 error.

See the following post for a detailed examination of these issues:

Strategies for resource-based 404 errors in ASP.NET MVC
http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/

Robert Harvey
Actually a controller not found would be handed to the "secondary system" if the secondary system could not handle it ... then you are right it should return a 404. A missing action on a controller - also 404
tyndall