C# 如何处理这个路由?
我有如下URL:C# 如何处理这个路由?,c#,asp.net-mvc,url,routing,routes,C#,Asp.net Mvc,Url,Routing,Routes,我有如下URL: /nl/blog(显示博客项目概述) /nl/blog/loont lekker koken en wordt eerlijkheid beloond(显示带有URL标题的博客项目) /nl/blog/waarom liever diëtist dan kok(显示带有URL标题的博客项目) 我已经为其定义了路线: A:使用约束articlepage=@“\d”路由“nl/blog/{articlepage}” B:路线“nl/博客” C:路由“nl/blog/{urlt
- /nl/blog(显示博客项目概述)
- /nl/blog/loont lekker koken en wordt eerlijkheid beloond(显示带有URL标题的博客项目)
- /nl/blog/waarom liever diëtist dan kok(显示带有URL标题的博客项目)
- A:使用约束articlepage=@“\d”路由“nl/blog/{articlepage}”
- B:路线“nl/博客”
- C:路由“nl/blog/{urlttitle}/{commentpage}”,带有约束commentpage=@“\d”
- D:路由“nl/blog/{urlttitle}”
- E:路由“nl/blog/{action}”
谢谢你的建议。回答我自己的问题: 对于问题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:“nl/blog/{articlepage}”
- defaultvalues:new{articlepage=UrlParameter.Optional}
- 约束条件:新建{articlepage=new isonationalOrmatchesRegex(@“\d”)
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);
}
}
公共类ExcludeConstraint:IRouteConstraint
{
私有只读列表_排除列表;
公共ExcludeConstraint(列表excludedList)
{
_excludedList=excludedList;
}
公共布尔匹配(HttpContextBase httpContext、路由路由、字符串参数名称、RouteValueDictionary值、RouteDirection RouteDirection)
{
var valueToCompare=(字符串)值[parameterName];
return!\u excludedList.Contains(valueToCompare);
}
}
路线D可以改变如下:
- url:“nl/blog/{urlttitle}”
- 约束:新的{urlttitle=new ExcludeConstraint(新列表(){“addarticle”、“addcomment”、“gettags”}))
UrlParameter。可选的commentPage声明。谢谢辅导员,这确实是答案的一部分!