Asp.net mvc 3 MVC 3路线中的hypen
这是我想要的url格式:/product-24-hid-35wh4-cx-dsgtx 如何将此URL映射到我的操作方法:Asp.net mvc 3 MVC 3路线中的hypen,asp.net-mvc-3,routing,custom-routes,Asp.net Mvc 3,Routing,Custom Routes,这是我想要的url格式:/product-24-hid-35wh4-cx-dsgtx 如何将此URL映射到我的操作方法: public ActionResult Product(int id) 这是我的路线代码: routes.MapRoute( "ProductDetail", "product-{id}-{name}", new { controller = "product", action = "detail", name = UrlPa
public ActionResult Product(int id)
这是我的路线代码:
routes.MapRoute(
"ProductDetail",
"product-{id}-{name}",
new { controller = "product", action = "detail", name = UrlParameter.Optional },
new string[] { "SphereLight.Controllers" }
);
但是,它不起作用;我用phil haack的RoutedBugger测试了这条路线,结果如下:
Key Value
name dsgtx
id 24-hid-35wh4-cx
controller product
action detail
只有id=24是正确的
总之,我需要一条路线来匹配:
/product-24
/product-24-
/product-24-hid-35wh4-cx-dsgtx
尝试在MapRoute中添加约束:
routes.MapRoute(
"ProductDetail",
"product-{id}-{name}",
new { controller = "product", action = "detail", name = UrlParameter.Optional },
new { id = @"\d+" }, // <-- change it for @"[^-]+", if it can be non-digit
new string[] { "SphereLight.Controllers" }
);
MyRouteHandler的实现
public class MyRouteHandler : MvcRouteHandler
{
private static readonly Regex ProductPattern = new Regex(@"product\-(\d+)\-?(.*)");
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var match = ProductPattern.Match(requestContext.RouteData.Values["controller"].ToString());
if (match.Length > 0)
{
requestContext.RouteData.Values["controller"] = "Home";
requestContext.RouteData.Values["action"] = "Detail";
requestContext.RouteData.Values["id"] = match.Groups[1].Value;
requestContext.RouteData.Values["name"] = match.Groups[2].Value;
}
return base.GetHttpHandler(requestContext);
}
}
因此,主要的想法是检查这些值是否与处理程序中的模式product id name
匹配,而不是试图在MapRoute
中进行匹配。
希望这有帮助。不起作用,路由调试器结果是{controller:product-26-hid-35wh11-cx-dsgtx,action:index},如果禁用mvc的默认路由,调试器结果是{any:product-24-hid-35wh4-cx-dsgtx,controller:NotFound,action:NotFound}Hmm。。。如果add
id=UrlParameter.Optional
?恐怕不是,id是找到产品的关键——找到解决方案,但解析器有点奇怪。见更新后。
public class MyRouteHandler : MvcRouteHandler
{
private static readonly Regex ProductPattern = new Regex(@"product\-(\d+)\-?(.*)");
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var match = ProductPattern.Match(requestContext.RouteData.Values["controller"].ToString());
if (match.Length > 0)
{
requestContext.RouteData.Values["controller"] = "Home";
requestContext.RouteData.Values["action"] = "Detail";
requestContext.RouteData.Values["id"] = match.Groups[1].Value;
requestContext.RouteData.Values["name"] = match.Groups[2].Value;
}
return base.GetHttpHandler(requestContext);
}
}