出现特定操作时,使用MVC路由覆盖控制器名称 [英] Use MVC routing to override controller name when presented with specific action

查看:93
本文介绍了出现特定操作时,使用MVC路由覆盖控制器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MVC4中指定一条路由,该路由会在显示特定操作名称的情况下忽略控制器名称.例如.

I'm attempting to specify a route in MVC4 that ignores a controller name if presented with a specific action name. For example.

mysite.com/AnyControllerNameHere/SpecificAction -让我指定在

mysite.com/AnyControllerNameHere/NotSpecificAction -将带我使用AnyControllerNameHere Controller和NotSpecificAction方法,例如MVC默认值.

mysite.com/AnyControllerNameHere/NotSpecificAction - Would take me the the AnyControllerNameHere Controller and NotSpecificAction method like the MVC default.

我已经尝试编写一些东西,但是它似乎并没有达到我想要的功能.完整的路由配置只是MVC的默认值,而我尝试这样做是为了……

I've attempted to code something up but it doesn't seem to do what I want. Full route config is just the MVC defaults plus me attempting to do this so...

    public static void RegisterRoutes(RouteCollection routes)
    {
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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


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

推荐答案

编写此代码时:

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" });

这篇关于出现特定操作时,使用MVC路由覆盖控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆