【问题标题】:How to handle this routing?如何处理这个路由?
【发布时间】:2011-12-13 22:59:32
【问题描述】:

我有类似的网址:

  • /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}" 约束 articlepage = @"\d"
  • B:路由“nl/blog”
  • C: 路由 "nl/blog/{urltitle}/{commentpage}" 带有约束 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" 映射到这个路由,并执行正确的操作方法。但是我想知道是否有更好的方法来处理这个问题?

感谢您的建议。

【问题讨论】:

  • 好问题。我对任何答案都很感兴趣。
  • 也许自定义路由约束可能是最优雅的解决方案?
  • 好的,对于问题 2,我自己找到了答案。我创建了一个名为 ExcludeConstraint 的自定义约束,并将路由 D 更改为:路由 "nl/blog/{urltitle}" 约束为 "new { urltitle = new ExcludeConstraint(new List() { "addarticle", "addcomment", "gettags"}) }));"。现在,我的网址保持干净,例如 /nl/blog/addcomment
  • 您可以对这些路由和您的要求进行的唯一更改是合并路由 C 和 D,并为 commentPage 添加 UrlParameter.Optional 声明。
  • 感谢辅导员本,这确实是答案的一部分!

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


【解决方案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 可以表示为一条路由:

  • 网址:“nl/blog/{articlepage}”
  • 默认值:新 { articlepage = UrlParameter.Optional }
  • 约束:新 { 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 更改为:

  • 网址:“nl/blog/{urltitle}”
  • 约束:new { urltitle = new ExcludeConstraint(new List() { "addarticle", "addcomment", "gettags"}) }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2015-05-24
    相关资源
    最近更新 更多