2015-10-15 68 views
0

当我尝试添加约束默认路由如下ASP.NET MVC:id为约束的缺省路由

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,5.2.3 MVC,VS 2015年和IIS快递10.0。

+0

嗯,你已经添加了一个约束它有效地使所需的ID与id参数。我猜你喜欢'yourhost /'或'yourhost /控制器/ action' –

+0

@Daniel,这是否真正使需要的网址,让你的错误?如果是这样,我怎么可以指定它应该是整数而已,但不能使需要它? – drty

+0

它是一个棘手的事情。我想你可以定义路由'{控制器}/{行动}/{ID}'那里他们都不是可选的,ID具有约束。然后另一条路线'{控制器}/{行动}'其中两个是可选的,有家庭/索引默认值 –

回答

0

好吧,我想你的问题,因为它可以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() } 
     ); 
0

没有尝试这样做,你可能想定义两个途径来实现你所需要的

routes.MapRoute(
       name: "Default1", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index"}, 
       constraints: new {[email protected]"\d+"} 
      ); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index",id= UrlParameter.Optional }    
      ); 

如果id为null,则回落到默认路由。