ASP.NET MVC 4 路由 - 控制器/ID 与控制器/动作/ID [英] ASP.NET MVC 4 Routes - controller/id vs controller/action/id

查看:30
本文介绍了ASP.NET MVC 4 路由 - 控制器/ID 与控制器/动作/ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如何组合两个路由配置,使两个 URL 都可以工作?如果在 SO 上已经有这样的问题,我很抱歉,我找不到任何东西.

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.

推荐答案

关键是先放更具体的路线.所以把Book"路线放在第一位.编辑 我猜您还需要一个约束来只允许数字匹配此路由的id"部分.结束编辑

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

并确保详细信息"操作中的id"参数是整数:

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

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

这样,"Books" 路由就不会捕获像 /users/create 这样的 URL(因为第二个参数被要求为一个数字),所以会掉到下一个(默认")路由.

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.

这篇关于ASP.NET MVC 4 路由 - 控制器/ID 与控制器/动作/ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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