2015-07-02 55 views
0

我要創建每個字符串匹配的MVC模式的路線,但所有這些的,我有這樣的路線:Asp.Net MVC - 創建匹配的一切,包含一些值,比如一個路線,但一些字符串

 context.MapRoute(
      "Users_Bootstrap", 
      "{ulrPrefix}/{*catchall}", 
      new { controller = "Start", action = "Index" }, 
      namespaces: new[] { "Fanapo.Web.Areas.Users.Controllers" }, 
      constraints: new { } 
     ); 

我想這條路線不匹配任何字符串urlPrefix參數是AccountAdmin...

事情是這樣的:ulrPrefix NOT IN [Account, Admin, ...]

餘噸應該用正則表達式解決這個問題,希望IRouteConstraint是最後一個選項。謝謝。

回答

0

使用路線約束求解,基於this answer

public class NotInRouteConstraint : IRouteConstraint 
{ 
    private readonly string _notInString; 

    public NotInRouteConstraint(string notInString) 
    { 
     _notInString = notInString; 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, 
     RouteDirection routeDirection) 
    { 
     if (string.IsNullOrEmpty(_notInString)) 
      return true; 

     var notList = _notInString.Split('|').Select(s => s.Trim().ToLower()).ToList(); 

     var value = values[parameterName] as string; 
     if (!string.IsNullOrEmpty(value)) 
     { 
      return !notList.Contains(value.ToLower()); 
     } 
     return true; 
    } 
} 

用法代碼:

//this is in another area 
     context.MapRoute(
      "Users_Bootstrap", 
      "{ulrPrefix}/{*catchall}", 
      new { controller = "Start", action = "Index" }, 
      constraints: new { ulrPrefix = new NotInRouteConstraint(RouteConfig.ReservedUrlPrefix.JoinStrings("|")) } 
     ); 

希望有另一個更好的解決方案。謝謝。


編輯


更多更快一點:

public class NotInRouteConstraint : IRouteConstraint 
{ 
    private readonly IEnumerable<string> _notInString; 

    public NotInRouteConstraint(IEnumerable<string> notInString) 
    { 
     _notInString = notInString; 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, 
     RouteDirection routeDirection) 
    { 
     if (_notInString == null) 
      return true; 

     var value = values[parameterName] as string; 
     if (!string.IsNullOrEmpty(value)) 
     { 
      return !_notInString.Contains(value.ToLower()); 
     } 
     return true; 
    } 
} 

context.MapRoute(
      "Users_Bootstrap", 
      "{ulrPrefix}/{*catchall}", 
      new { controller = "Start", action = "Index" }, 
      constraints: new { ulrPrefix = new NotInRouteConstraint(RouteConfig.ReservedUrlPrefix.Select(s=>s.Trim().ToLower())) } 
     ); 
相關問題