ASP MVC route all requests for a controller to the

2020-04-10 01:39发布

问题:

I have a public page that has client side routing. I would like all urls of the form Public/* to be routed to PublicController/Index.

I tried this:

routes.MapRoute(
                name: "Public",
                url: "Public/{clientRoute}",
                defaults: new { controller = "Public", action = "Index", id = UrlParameter.Optional }
            );

and this works for urls of type Public/someRoute but does not work for a url of the form Public/someRoute/secondRoute or for Public/someRoute/secondRoute/thirdRoute etc.

回答1:

You were really close! This should take care of what you are looking to do.

routes.MapRoute(
                name: "Public",
                url: "Public/{*clientRoute}",
                defaults: new { controller = "Public", action = "Index"}
            );

Note the star in the URL parameter, this tells it to function as a "catch all". Now, anything starting with Public/ will go to this controller/action. Also, if you don't need the id parameter, don't concern yourself with specifying a default for it.