我有这样的网址:
- /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: route "nl/blog/{urltitle}/{commentpage}"with constraint commentpage = @"\d"
- D: 路由“nl/blog/{urltitle}”
问题 1:这工作正常,但也许有更少路由的更好解决方案?
问题2:为了添加一篇新文章,我在BlogController 中有一个 Action 方法AddArticle。当然,对于上面定义的路由,url“/nl/blog/addarticle”将映射到路由 D,其中 addarticle 将是 urltitle,当然这是不正确的。因此我添加了以下路线:
- E: 路由“nl/blog/_{action}”
现在 url "/nl/blog/_addarticle"映射到这个路由,并执行正确的操作方法。但是我想知道是否有更好的方法来处理这个问题?
感谢您的建议。
最佳答案
我自己的问题的答案:
对于第一个问题,我创建了一个自定义约束 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}"
- 默认值:新的 { 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 更改为:
- 网址:“nl/博客/{urltitle}”
- 约束:new { urltitle = new ExcludeConstraint(new List() { "addarticle", "addcomment", "gettags"}) }));
关于c# - 如何处理这个路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873091/