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

无人久伴 提交于 2019-11-28 07:33:24
McGarnagle

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

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:

// "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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!