我有一个 ASP.Net 应用程序,它有一个名为“客户”的区域。这个区域有一个同名的 Controller ,只有一个名为 Index 的方法。
我定义了以下路由:
context.MapRoute(null,
"Customers/{controller}/{action}",
new { controller = "customers", action = "Index" }
);
这允许我导航到使用以下 URL 导航到我的 Customers Controller 上的索引方法。
MyDomain/Customers
在我的客户区,我还有另一个名为产品的 Controller 。它有许多方法可以让我使用产品实体(目前大部分由 Visual Studio 自动生成)。
使用我当前的路线,我可以使用这样的 URL 导航到产品 Controller :
MyDomain/Customers/Products (shows the index page of the products controller) MyDomain/Customers/Products/Create (Shows a page to add new products). MyDomain/Customers/Products/Details?id=1234 (Show the product with the id of 1234)
现在我想要做的是使用更加用户友好的 URL 导航到详细信息页面,例如:
MyDomain/Customers/Products/1234
我已经定义了一个看起来像这样的新路由:
context.MapRoute(null,
"Customers/Products/{id}",
new { controller = "Products", action = "Details" }
);
路线是在我演示的第一条路线之前定义的。 这允许我根据需要导航到产品页面,但是我无法再导航到我的产品 Controller 上的其他方法。
例如以下网址
MyDomain/Customers/Products/Create
给我以下错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Details(Int32)'
如果我更改路由的顺序,那么我可以导航到我的产品 Controller 上的所有方法,但我的详细信息 URL 将恢复为具有查询参数的旧格式。
如果我将路线更新为如下所示:
context.MapRoute(null,
"Customers/Products/{id}",
new { controller = "Products", action = "Details", id = UrlParameter.Optional }
);
然后我仍然遇到同样的问题。
谁能告诉我如何构建我的路线以获得我想要的结果?总结:
- 如果我导航到“客户”区域,我希望我的 URL 看起来像“MyDomain/Customers”
- 如果我导航到产品详细信息页面,我希望我的 URL 看起来像“MyDomain/Customers/Products/1234”。
- 如果我导航到任何其他产品页面,我希望我的 URL 看起来像“MyDomain/Customers/Products/Create”
最佳答案
如果 ID 始终是 int,那么您可以像这样向路由添加约束:
context.MapRoute(null,
"Customers/Products/{id}",
new {controller = "Products", action = "Details", id = UrlParameter.Optional},
new {id = @"\d+"} // Constraint to only allow numbers
);
关于c# - 使用 ID 或操作名称的 ASP.NET MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070460/