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

和自甴很熟 提交于 2019-11-29 11:34:59

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!