我想要根据部门名称和产品名称进行自定义路由。例如/ mobiles / nokia-6303
当我打电话给产品页面时,它工作正常。在控制器和动作方法正在执行的时候,默认情况下我正在调用除主页之外的产品页面以外的其他时间
defaults: new { controller = "ContentPage", action = "ProductDetail" }
如何避免这个问题?
routes.MapRoute(
name: "ProductDetailsPage",
url: "/{DepartmentName}/{ProductName}",
defaults: new { controller = "ContentPage", action = "ProductDetail" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
提前致谢 拉杰什
答案 0 :(得分:2)
您的路线完全相同。无法区分/DepartmentName/ProductName
和/Controller/Action
。您需要URL中的其他内容才能区分这两件事,例如:
routes.MapRoute(
name: "ProductDetailsPage",
url: "/Products/{DepartmentName}/{ProductName}",
defaults: new { controller = "ContentPage", action = "ProductDetail" }
);
然后导航到/ products / departmentname / productname
答案 1 :(得分:0)
对Ant P的优秀建议进行略微修改可能是将文本放在部门名称和产品名称之间?
routes.MapRoute(
name: "ProductDetailsPage",
url: "/{DepartmentName}/Products/{ProductName}",
defaults: new { controller = "ContentPage", action = "ProductDetail" }
);
或者之后有详细信息:
routes.MapRoute(
name: "ProductDetailsPage",
url: "/{DepartmentName}/{ProductName}/details",
defaults: new { controller = "ContentPage", action = "ProductDetail" }
);
这些网址方法中的任何一种都可能超过您的“搜索引擎优化工作小组”,因为它会在网址中包含相关信息。
答案 2 :(得分:0)
正如其他答案所述,路由系统无法区分{controller}/{action}
和{DepartmentName}/{ProductName}
。
您可以通过添加constraint to a route来解决此问题。如果未满足约束,则路由将与URL不匹配。您可能需要创建IRouteConstraint的自定义实现。我看到两个选择:
为{controller} / {action}路由创建一个约束,该约束将包含可能使用默认URL模式的控制器名称列表
为{DepartmentName} / {ProductName}路由创建约束,该约束将检查数据库(或某些内存缓存)部门名称和产品名称是否与某个产品匹配
答案 3 :(得分:0)
最后我使用路由配置本身修复了这个问题,请找到下面的代码。
foreach (var d in departmentTranslation)
{
routes.MapRoute(
"ContentPage" + d.Name,
d.Name + "/{ProductName}",
new
{
controller = "ContentPage",
action = "ProductDetails",
id = d.DepartmentId,
ProductName = UrlParameter.Optional
});
}