当我尝试将约束添加到默认路由时,如下所示
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
}
并运行该网站,我得到了:
HTTP错误403.14 - 禁止错误
Web服务器配置为不列出此目录的内容。
这条带有约束的单行会导致问题。当它被评论时,该网站正在按预期运行。我甚至能够在新创建的MVC项目上本地重现它。
这是某种错误,还是我不了解路线限制的关键因素?
我使用.NET 4.5.2,MVC 5.2.3,VS 2015和IIS Express 10.0。
答案 0 :(得分:1)
好的,我想你的问题和解决方案可以find here。
适合您情况的解决方案:
public class NullableConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest && parameterName == "id")
{
// If the userId param is empty (weird way of checking, I know)
if (values["id"] == UrlParameter.Optional)
return true;
// If the userId param is an int
int id;
if (Int32.TryParse(values["id"].ToString(), out id))
return true;
}
return false;
}
}
你的路线:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { id = new NullableConstraint() }
);
答案 1 :(得分:0)
Haven没试过这个,你可能想要定义两条路线来实现你需要的东西
routes.MapRoute(
name: "Default1",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index"},
constraints: new {id=@"\d+"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",id= UrlParameter.Optional }
);
如果id为null,则返回默认路由。