2015-10-15 69 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,則回落到默認路由。