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

查看:212
本文介绍了ASP.NET MVC 4路 - 控制器/ ID VS控制器/操作/ 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

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

如何在两个路由配置结合,从而这两个网址工作?
我很抱歉,如果已经有这样的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.

推荐答案

关键是要先把更具体的路线。因此,首先把书的路线。 修改我猜你还需要一个约束,只允许数字匹配这条路线的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参数是一个int:

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

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

这样的话,书的路线不会赶上像 /用户URL /创建(因为第二个参数reqiured是一个数字),等会通过转到下一个(默认)的路线。

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 VS控制器/操作/ ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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