MVC Url Routing +添加其他参数

时间:2013-11-14 09:16:11

标签: asp.net asp.net-mvc

我有一个像http://mysite.ef.com/mine这样的网址。它内部需要重定向到

http://mysite.ef.com/Product/ViewProduct/2。最后一个参数(即2)必须从第一个url的最后一个参数(在这种情况下,值是“我的”)中导出,方法是点击数据库以查看它是否有效以及是否有效获取正确的id。我们如何使用Url Routing完成它。我可以使用自定义约束验证它,但如何使用此获取的值重写URL。

此致 RAGHAV

1 个答案:

答案 0 :(得分:0)

让您的路由配置如下所示:

routes.MapRoute(
      name: "ProductRouting",
      url: "{id}",
      defaults: new { controller = "Product", action = "ProductView", id = UrlParameter.Optional },
      namespaces: new[] { "YourApp.Controllers" }
);

请注意,因为通常的默认路由看起来像这样,如果您只传递一个通常只指定控制器的参数,但在您的情况下,它将指定产品ID。

routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional },
      namespaces: new[] { "YourApp.Controllers" }
);

如果您以某种方式需要它来执行查找并确定mine对应于产品2,那么您的ProductView ActionMethod需要接受字符串并执行简单的查找。