且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

出现特定操作时,使用MVC路由覆盖控制器名称

更新时间:2023-02-12 23:31:59

编写此代码时:

routes.MapRoute(
    "SpecificAction",
    "{controller}/SpecificAction",
    new { controller = "Home", action = "SpecificAction" });

您打算覆盖控制器.但是,第三个参数不能用于 override 参数.它仅为URL尚未提供的任何参数提供默认值.

you intend to override the controller. However, the third argument cannot be used to override parameters. It merely provides the defaults for any parameters that aren't already provided by the URL.

因此,您需要的是设置控制器参数的路由模板,以便默认设置生效:

So what you need is a route template which doesn't set the controller parameter, so that the default takes effect:

routes.MapRoute(
    name: "SpecificAction",
    url: "{ignored}/SpecificAction",
    defaults: new { controller = "Home", action = "SpecificAction" });