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

前端 未结 2 1160
南笙
南笙 2020-12-19 14:03

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

相关标签:
2条回答
  • 2020-12-19 14:28

    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.

    0 讨论(0)
  • 2020-12-19 14:34

    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.

    0 讨论(0)
提交回复
热议问题