ASP.NET MVC: Many Routes & # 8594; always only one controller

I have a very simple question. My ASP.NET MVC-based site may have many URLs, but all of them should lead to the same controller. How to do it?

I suppose I need magic in Global.asax, but I don't know how to create a route that redirects any URL to a specific controller.

For example, I have url / about, / product / id, etc., but all of them should really be presented to the content / display, where the parts of the URL will be recognized, and a decision about what information will be displayed. This is similar to a CMS if you cannot predefine routes. Is this information enough?

thanks

+4
source share
2 answers

It sounds like a terrible idea, but if necessary,

routes.MapRoute( "ReallyBadIdea", "{*url}", new { controller = "MyFatController", action = "MySingleAction" } ); 

This directs everything to a single action in one controller. There also {* path} and other URL patterns should be a little more flexible.

+20
source

Ideally, you should try and specify your routes, for example, if you have the URL / products / 42, and you want it to go to the general controller, you should explicitly specify it as

 routes.MapRoute( "Poducts", "products/{id}", new { controller = "Content", action = "Show", id = UrlParameter.Optional } ); 

then you must specify a different route for something else, e.g. / customers / 42

 routes.MapRoute( "Customers", "customers/{id}", new { controller = "Content", action = "Show", id = UrlParameter.Optional } ); 

this may seem a little verbose, and creating one route may seem cleaner, but the problem is in one route - you will never get 404 and will have to handle such things in code.

+1
source

All Articles