如何处理这种路由

本文关键字:路由 处理 何处理 | 更新日期: 2023-09-27 18:12:16

我有这样的URL:

  • /nl/blog(显示博客项目的概述)
  • /nl/blog/loont-lekker- koken-wordt-eerlijkheid - below(显示带有url标题的博客项目)
  • /nl/blog/waarom-liever-diëtist-dan-kok(显示带有url标题的blog项目)

,我已经为它定义了路由:

  • A: route "nl/blog/{articlepage}" with constraint articlepage = @"'d"
  • B: route "nl/blog"
  • C: route "nl/blog/{urltitle}/{commentpage}" with constraint commentpage = @"'d"
  • D: route "nl/blog/{urltitle}"

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

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

  • E: route "nl/blog/_{action}"

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

谢谢你的建议

如何处理这种路由

回答我自己的问题:

对于问题1,我创建了一个自定义约束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:"问/博客/{articlepage}"
  • defaultvalues: new {articlepage = UrlParameter。可选}
  • 约束:new {articlepage = new IsOptionalOrMatchesRegEx(@"'d")

对于问题2,我创建了一个exudeconconstraint:

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);            
    }
}

Route D可以这样修改:

  • url:"问/博客/{urltitle}"
  • constraints: new {urltitle = new excludeconconstraint (new List() {"addarticle", "addcomment", "gettags"})});