2012-12-21 56 views
5

爲什麼路線http://localhost:2222/2012-adidas-spring-classic/37不能從下面的路線匹配中獲取?我收到一個404錯誤。Route Constraint Isnt適用於ASP.NET MVC

 public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
      routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" }); 
      routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" }); 

      #region API 

      routes.MapRouteLowercase(
      "NamedHomeEvent", 
      "{year}-{name}/{Id}", 
      new { controller = "Event", action = "Index", year = DateTime.Now.Year }, 
      new { year = @"\d{4}", Id = @"\d+" } 
      ); 



    public virtual ActionResult Index(int? id, int? year, string name) 
     { 
+0

你也可以使用http://getglimpse.com/調試路線(以及更多) (http://getglimpse.com/Help/Plugin/Routes) – robasta

回答

4

路由引擎不能幫你在這裏。你可以寫一個自定義路由來處理這種情況:

public class MyRoute : Route 
{ 
    public MyRoute() 
     : base(
      "{year-name}/{id}", 
      new RouteValueDictionary(new { controller = "Event", action = "Index", id = UrlParameter.Optional }), 
      new RouteValueDictionary(new { id = @"\d*" }), 
      new MvcRouteHandler() 
     ) 
    { 
    } 

    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var routeData = base.GetRouteData(httpContext); 
     if (routeData == null) 
     { 
      return null; 
     } 

     var yearName = (string)routeData.Values["year-name"]; 
     if (string.IsNullOrWhiteSpace(yearName)) 
     { 
      return null; 
     } 

     var parts = yearName.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries); 
     if (parts.Length < 2) 
     { 
      return null; 
     } 

     var year = parts.First(); 
     int yearValue; 
     if (!int.TryParse(year, out yearValue)) 
     { 
      return null; 
     } 

     var name = parts.Last(); 

     routeData.Values.Add("year", year); 
     routeData.Values.Add("name", name); 

     return routeData; 
    } 
} 

,然後註冊此路線:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
    routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" }); 
    routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" }); 

    routes.Add("NamedHomeEvent", new MyRoute()); 
} 
+0

我相信這隻會與T4MVC無關 –