mimic
mimic

Reputation: 5224

ASP.NET MVC: Many routes -> always only one controller

I have very simple question. My site, based on ASP.NET MVC, can have many urls, but all of them should bring to the one controller. How to do that?

I suppose I need some magic in Global.asax but I don't know how to create route that will redirect any url to the specific controller.

For example I have url /about, /product/id etc. but all of them should be really bring to the content/show where the parts of url will be recognized and the decision what information to show will be make. It's some like CMS when you cannot define routes in advance. Is this information enough?

Thanks

Upvotes: 4

Views: 6279

Answers (2)

T00ks
T00ks

Reputation: 172

Ideally you should try and specific with your routes, for example if you have a URL that is /products/42 and you want it to go to a generic controller you should specify it explicitly like

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

then you would specify another route for something else like /customers/42

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

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

Upvotes: 2

blowdart
blowdart

Reputation: 56490

This sounds like a horrible idea, but, well, if you must;

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

This routes everything to a single action in a single controller. There's also {*path} and other URL patterns should you want slightly more flexibility.

Upvotes: 21

Related Questions