asp.net-mvc ASP.NET MVC 4 路由 - 控制器/ID 与控制器/动作/ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18038284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:04:21  来源:igfitidea点击:

ASP.NET MVC 4 Routes - controller/id vs controller/action/id

asp.net-mvcasp.net-mvc-4routesasp.net-mvc-routing

提问by Arman Bimatov

I'm trying to add a route to the default one, so that I have both urls working:

我正在尝试将路由添加到默认路由,以便我的两个 url 都可以工作:

  1. http://www.mywebsite.com/users/create
  2. http://www.mywebsite.com/users/1
  1. http://www.mywebsite.com/users/create
  2. http://www.mywebsite.com/users/1

This will make the first route work:

这将使第一条路线工作:

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

However, the second route won't work obviously.

但是,第二条路线显然不起作用。

This will make the second route work, but will break the first one:

这将使第二条路线工作,但会破坏第一条路线:

routes.MapRoute(
     name: "Book",
     url: "books/{id}",
     defaults: new { controller = "users", action = "Details" }
);

How to combine the two route configurations so that both URLs work? I apologize if there is already a question like this on SO, I wasn't able to find anything.

如何组合两个路由配置,使两个 URL 都能工作?如果在 SO 上已经有这样的问题,我深表歉意,我找不到任何东西。

回答by McGarnagle

The key is to put more specific routes first. So put the "Book" route first. EditI guess you also need a constraint to only allow numbers to match the "id" part of this route. End edit

关键是把更具体的路线放在第一位。所以把“Book”路线放在第一位。 编辑我猜你还需要一个约束来只允许数字匹配这条路线的“id”部分。结束编辑

routes.MapRoute(
    name: "Book",
    url: "books/{id}",
    defaults: new { controller = "users", action = "Details" },
    constraints: new { id = @"\d+" }
);

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

And ensure that the "id" parameter in your "Details" action is an int:

并确保“详细信息”操作中的“id”参数是一个整数:

// "users" controller
public ActionResult books(int id)
{
    // ...
}

This way, the "Books" route will not catch a URL like /users/create(since the second parameter is reqiured to be a number), and so will fall through to the next ("Default") route.

这样,“Books”路由将不会捕获类似的 URL /users/create(因为第二个参数需要为数字),因此将落入下一个(“默认”)路由。