如何处理这种路由?

时间:2011-10-24 08:42:27

标签: c# asp.net-mvc url routing routes

我的网址如下:

  • / nl / blog(显示博客项目概述)
  • / nl / blog / loont-lekker-koken-en-wordt-eerlijkheid-beloond(显示带有urltitle的博客项目)
  • / nl / blog / waarom-liever-diëtist-dan-kok(用urltitle显示博客项目)

我为其定义了路线:

  • A:路线“nl / blog / {articlepage}”,带约束条款页= @“\ d”
  • B:路线“nl / blog”
  • C:使用约束评论页面路线“nl / blog / {urltitle} / {commentpage}”= @“\ d”
  • D:路线“nl / blog / {urltitle}”

问题1:这种方法很好,但也许有更好的解决方案,路线更少?

问题2:添加新文章,我在BlogController中有一个动作方法AddArticle。当然,使用上面定义的路由,URL“/ nl / blog / addarticle”将映射到路径D,其中addarticle将是当然不正确的urltitle。因此我添加了以下路线:

  • E:路线“nl / blog / _ {action}”

现在url“/ nl / blog / _addarticle”映射到此路由,并执行正确的操作方法。但我想知道是否有更好的方法来解决这个问题?

感谢您的建议。

1 个答案:

答案 0 :(得分: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可以用一种路线表示:

  • url:" nl / blog / {articlepage}"
  • defaultvalues:new {articlepage = UrlParameter.Optional}
  • 约束:new {articlepage = new IsOptionalOrMatchesRegEx(@" \ d")

对于问题2,我创建了一个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:&#34; nl / blog / {urltitle}&#34;
  • constraints:new {urltitle = new ExcludeConstraint(new List(){&#34; addarticle&#34;,&#34; addcomment&#34;,&#34; gettags&#34;})})); < / LI>