在 mvc 中的控制器名称后传递查询字符串

passing query string after the controller name in mvc

我正在尝试在控制器名称后传递 mvc 中的参数

我加了

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

这没有用

我也试过了url: "Product/{id}",

但是如果我删除上面的行(post下面的行),它就可以工作

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

注册路线的顺序很重要。使用与请求匹配的第一个路由。如果我理解正确的话,你原来有:

routes.MapRoute(
    name: "Default",
...

routes.MapRoute(
    name: "Product",

默认路由非常通用,因为它首先被注册,所以它一直被用于您的所有请求,有效地隐藏了产品路由。

注册路由的正确方法是从最具体的路由开始,最后注册最通用的路由。所以在你的情况下它应该被逆转:

routes.MapRoute(
    name: "Product",
...
routes.MapRoute(
    name: "Default",

在这种情况下,使 "id" 参数成为 必需的 参数而不是可选参数更有意义.您可能也不希望它成为一个 slug ({*id})。这将有助于确保如果您的 Product 路由与请求不匹配,路由框架将尝试列表中的下一条路由(在本例中为 Default)。

要绝对确保在没有匹配项时它会丢失,您还可以添加路由约束以确保 "id" 是数字,就像 route constraint example on MSDN.

routes.MapRoute(
    name: "Product",
    url: "Product/{id}",

    // id has no default value, which makes it required in order to match
    defaults: new { controller = "Product", action = "Index" },

    // (optional) adding a constraint will make sure the id is only digits
    constraints: new { id = @"\d+" }
);

// You will only end up here if the above route does not match, 
// so it is important that you ensure that it CAN miss.
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);