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

此生再无相见时 提交于 2019-11-28 04:31:42

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5863984/asp-net-mvc-many-routes-always-only-one-controller

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