Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Catch All Route And Default Route

In trying to get my application to produce 404 errors correctly, I have implemented a catch all route at the end of my route table, as shown below:

 routes.MapRoute(             "NotFound", _            "{*url}", _            New With {.controller = "Error", .action = "PageNotFound"} _        ) 

However, to get this working, I had to remove the default route:

{controller}/action/{id} 

But now that the default has been removed, most of my action links no longer work, and the only way I have found to get them working again is to add individual routes for each controller/action.

Is there a simpler way of doing this, rather than adding a route for each controller/action?

Is it possible to create a default route that still allows the catch all route to work if the user tries to navigate to an unknown route?

like image 485
Sean Taylor Avatar asked Oct 22 '10 21:10

Sean Taylor


2 Answers

Use route constraints

In your case you should define your default route {controller}/{action}/{id} and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.

So when someone would request a resource that fails a constraint the catch-all route would match the request.

So. Define your default route with route constraints first and then the catch all route after it:

routes.MapRoute(     "Default",     "{controller}/{action}/{id}",     new { controller = "Home", action = "Index", id = UrlParameter.Optional },     new { controller = "Home|Settings|General|..." } // this is basically a regular expression ); routes.MapRoute(     "NotFound",     "{*url}",     new { controller = "Error", action = "PageNotFound" } ); 
like image 166
Robert Koritnik Avatar answered Sep 22 '22 18:09

Robert Koritnik


//this catches all  requests routes.MapRoute(     "Error",     "{*.}",      new { controller = "PublicDisplay", action = "Error404" }  ); 

add this route at the end the routes table

like image 24
Praveen Prasad Avatar answered Sep 23 '22 18:09

Praveen Prasad