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

前端 未结 2 1167
南笙
南笙 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: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.

提交回复
热议问题