导航

09-001 Routing 之 IRouteConstraint 系列

Posted on 2015-04-07 14:30  DotNet1010  阅读(191)  评论(0)    收藏  举报

路由约束是对routeKey的一种限制,比如限制整型,限制长度 接口代码:

       bool Match([NotNull] HttpContext httpContext,
                   [NotNull] IRouter route,
                   [NotNull] string routeKey,
                   [NotNull] IDictionary<string, object> values,
                   RouteDirection routeDirection);

 比较重要的两个参数是:routeKey 要限制的内容 比如 tempate: {controller}/{action}/{id} 中的 controller 或者 action 或者 id 。

values 是URL 结合 template 来产生的字典;

比如 URL是: www.testsite.com/Home/Index/5  结合 template: {controller}/{action}/{id}

产生的对应的字典为:values["controller"]="Home"; values["action"]="Index"; values["id"]="5";

接口的实现类有如下一些:

//values 中是否包含routeKey 并且值是 int  使用方法如: template: {controller}/{action}/{id:int}
public class IntRouteConstraint : IRouteConstraint{}

 看下面一个列表:

				// Type-specific constraints 指定类型约束
				{ "int", typeof(IntRouteConstraint) },			   //举例: {id:int}
				{ "bool", typeof(BoolRouteConstraint) },		   //举例: {id:bool}
				{ "datetime", typeof(DateTimeRouteConstraint) },   //举例: {id:datetime}
				{ "decimal", typeof(DecimalRouteConstraint) },	   //举例: {id:decimal}
				{ "double", typeof(DoubleRouteConstraint) },	   //举例: {id:double}
				{ "float", typeof(FloatRouteConstraint) },		   //举例: {id:float}
				{ "guid", typeof(GuidRouteConstraint) },		   //举例: {id:guid}
				{ "long", typeof(LongRouteConstraint) },		   //举例: {id:long}
				 // Length constraints
				{ "minlength", typeof(MinLengthRouteConstraint) },	//  {id:minlength(3)}
				{ "maxlength", typeof(MaxLengthRouteConstraint) },	//  {id:maxlength(3)}
				{ "length", typeof(LengthRouteConstraint) },		//  {id:length(3)}

				// Min/Max value constraints
				{ "min", typeof(MinRouteConstraint) },				 //  {id:min(3)}
				{ "max", typeof(MaxRouteConstraint) },				 //  {id:max(100)}
				{ "range", typeof(RangeRouteConstraint) },			 //  {id:range(3,100)}  大于等于 并且 小于等于

				// Regex-based constraints
				{ "alpha", typeof(AlphaRouteConstraint) },			//举例: {id:alpha} 只包含字母 a-z 大写或者小写
				{ "regex", typeof(RegexInlineRouteConstraint) },	        //举例: {id:regex(^[a-z]*$)}  

				{"required", typeof(RequiredRouteConstraint) },	   //  {id:required} 有且不为空 不为null