我的网址如下:
我为其定义了路线:
问题1:这种方法很好,但也许有更好的解决方案,路线更少?
问题2:添加新文章,我在BlogController中有一个动作方法AddArticle。当然,使用上面定义的路由,URL“/ nl / blog / addarticle”将映射到路径D,其中addarticle将是当然不正确的urltitle。因此我添加了以下路线:
现在url“/ nl / blog / _addarticle”映射到此路由,并执行正确的操作方法。但我想知道是否有更好的方法来解决这个问题?
感谢您的建议。
答案 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可以用一种路线表示:
对于问题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,如: