2011-10-24 60 views
6

我有這樣的URL:如何處理這個路由?

  • /EN /博客(顯示概述或博客條目)
  • /EN /博客/支付偉大,烹飪和IS-公平回報(顯示博客與項目urltitle)
  • /EN /博客/爲什麼,而高於營養師,廚師(顯示了urltitle博客項目)

對我有多少追隨者定義的路由

  • 答:路線 「恩/博客/ {文章頁}」 與約束文章頁面= @ 「\ d」
  • B:路線 「恩/博客」
  • C:路線「恩/博客/ {urltitle}/{評論頁} 「有約束的評論頁= @」 \ d 「
  • d:路線」 恩/博客/ {urltitle}「

問題1:這工作得很好,但也許有較少的軌道更好的解決方案?

問題2:添加新的文章中,我已經在博客控制器的操作方法AddArticle。當然,與途徑上面定義的URL「/ EN /博客/ addarticle」將映射到路徑d,其中addarticle將是urltitle,這是不正確的,當然。因此,我增加了以下路線:

  • E:路線 「COM /博客/ _ {行動}」

,因此現在的URL 「/ EN /博客/ _addarticle」 文件夾,這條路線,並執行正確的操作方法。但我想知道是否有更好的方法來處理這個問題?

謝謝你的建議。

+1

不錯的問題。我對任何答案都很感興趣。 – Phil

+0

也許自定義路由約束可能是最優雅的解決方案? –

+0

好的,對於問題2我自己找到了答案。我創建了一個名爲ExcludeConstraint的自定義約束,並將路由D更改爲:route「nl/blog/{urltitle}」,約束爲「new {urltitle = new ExcludeConstraint(new List (){」addarticle「,」addcomment「,」gettags 「})}));」。現在,我的網址保持乾淨,如/ nl/blog/addcomment –

回答

4

答案我自己的問題:

對於問題一,我創建了一個自定義的約束IsOptionalOrMatchesRegEx:

public class IsOptionalOrMatchesRegEx : IRouteConstraint 
{ 
    private readonly string _regEx; 

    public IsOptionalOrMatchesRegEx(string regEx) 
    { 
     _regEx = regEx; 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     var valueToCompare = values[parameterName].ToString(); 
     if (string.IsNullOrEmpty(valueToCompare)) return true; 
     return Regex.IsMatch(valueToCompare, _regEx); 
    } 
} 

然後,點A和B可以在一個路線中過表達:

  • 網址: 「COM /博客/文章{PAGE}」
  • 默認值:新的文章頁面= {UrlParameter。可選}
  • 約束:新的{articlepage =新IsOptionalOrMatchesRegEx(@ 「\ d」)

對於問題2,I創建ExcludeConstraint:

public class ExcludeConstraint : IRouteConstraint 
{ 
    private readonly List<string> _excludedList; 

    public ExcludeConstraint(List<string> excludedList) 
    { 
     _excludedList = excludedList; 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     var valueToCompare = (string)values[parameterName]; 
     return !_excludedList.Contains(valueToCompare);    
    } 
} 
然後

路線d可以被改變,如:

  • URL: 「NL /博客/ {urltitle}」
  • 約束:新的{urltitle =新ExcludeConstraint(新列表(){「一ddarticle「,」addcomment「,」gettags「})}));
相關問題