路由约束asp.net mvc

Bub*_*oon 5 asp.net asp.net-mvc asp.net-mvc-4

这是我的Route配置:

routes.MapRoute(
            name: "AdsCategories",
            url: "Ads/{key}",
            defaults: new { controller = "Ads", action = "Index" },
            //constraints: new { key =  },
            namespaces: new string[] { "Vprok.Controllers" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "Vprok.Controllers"}
        );
Run Code Online (Sandbox Code Playgroud)

如何创建约束"AdsCategories"?我需要使用默认路由,如果控制器中的操作"Ads"== {key}.

Dar*_*rov 9

所以基本上,如果{key}是现有的操作,您希望它由默认路由处理而不是使用控制器Index上的操作Ads

为了实现这一点,您可以列出键约束中的所有可能操作:

routes.MapRoute(
    name: "AdsCategories",
    url: "Ads/{key}",
    defaults: new { controller = "Ads", action = "Index" },
    constraints: new { key = @"^create|update|delete" },
    namespaces: new string[] { "Vprok.Controllers" }
);
Run Code Online (Sandbox Code Playgroud)

在此示例中,AdsCategories仅当URL不是ads/createads/update或时,路由才匹配ads/delete.例如ads/foobar将匹配.