进出口试图做这样的事情:
Im trying to do something like this:
routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional });这让我当我尝试加载404页,我认为错误,我试着让URL看起来像这样:www.tables/productName/ID。我如何能做到不添加强类型一句话是这样的:
It gives me error when im trying to load page 404 i think, Im trying to make the url look like this: www.tables/productName/ID . How can i do it without adding a strong type word like this:
routes.MapRoute("Product", "Products/{product}/{id}", ... )路由的其余部分:
rest of the routes:
routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional }); routes.MapRoute("Category", "Category/{category}/{template}", new { action = "Index", controller = "Category", category = UrlParameter.Optional, template = UrlParameter.Optional }); routes.MapRoute("Profile", "Profile/{fullName}", new { action = "Index", controller = "Profile", fullName = UrlParameter.Optional }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } );感谢。
推荐答案您的问题是,产品路线将匹配一切不分类或配置文件启动。
Your problem is that the Product route will match everything not starting with Category or Profile.
我想将产品路线只是缺省路由之前和使用IRouteConstraint使得其不匹配的非产品
I would place the product route just before the default route and use a IRouteConstraint such that it doesn't match non products.
code样品:
Code sample:
routes.MapRoute("Category", "Category/{category}/{template}", new { action = "Index", controller = "Category", category = UrlParameter.Optional, template = UrlParameter.Optional }); routes.MapRoute("Profile", "Profile/{fullName}", new { action = "Index", controller = "Profile", fullName = UrlParameter.Optional }); routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional }, new { product = new ProductRouteConstraint() }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } );和路径约束:
public class ProductRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.IncomingRequest && parameterName.ToLowerInvariant() == "product") { var productName = values[parameterName] as string; if (productName == null) return false; var productId = values["id"] as string; if (productId == null) returns false; return ProductCatalogue.HasProductById(productId); } return false; } }该器产品目录显然应该有,但是你查找的产品在你的系统所取代。
The ProductCatalogue should obviously be replaced with however you lookup products in your system.
更多推荐
与动态路由MVC 3路由帮助
发布评论