c# - 使用 ID 或操作名称的 ASP.NET MVC 路由

标签 c# asp.net-mvc asp.net-mvc-routing

我有一个 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 }
    );

然后我仍然遇到同样的问题。

谁能告诉我如何构建我的路线以获得我想要的结果?总结:

  1. 如果我导航到“客户”区域,我希望我的 URL 看起来像“MyDomain/Customers”
  2. 如果我导航到产品详细信息页面,我希望我的 URL 看起来像“MyDomain/Customers/Products/1234”。
  3. 如果我导航到任何其他产品页面,我希望我的 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/

相关文章:

c# - 部分代码覆盖率 C# - Nunit

asp.net-mvc - 将 PagedList 与 ViewModel 结合使用

c# - 虚拟目录中的 ASP.NET MVC

asp.net - 即使 F5 (big-ip) 正在处理 ssl,ASP.NET MVC 3 如何知道将 https 放在链接上?

c# - 自定义 map 路线

c# - 如何防止 DateTime 在带有区域性信息的 XML 中序列化?

c# - Visual Studio 复制设置为 "Do not copy"的 dll 文件

C# Winform CollectionPropertiesEditor - 如何根据运行时条件隐藏内置 PropertyGrid 中的某些属性

c# - Grid.Mvc 表 css 类

asp.net-mvc-routing - ASP.NET MVC 区域 : How to hide "Area" name in URL?