导航

09-007 Routing 之 RouteOptions

Posted on 2015-04-07 18:07  DotNet1010  阅读(289)  评论(0)    收藏  举报

这个类只有一个属性 ContraintMap

  public IDictionary<string, Type> ConstraintMap

 具体包含的内容

  private static IDictionary<string, Type> GetDefaultConstraintMap()
        {
            return new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase)
			{
				// 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
			};
        }

当然如果有需要可以实现自己的约束;并添加到里面。

 private class TestRouteConstraint : IRouteConstraint
        {
            public TestRouteConstraint(string pattern)
            {
                Pattern = pattern;
            }

            public string Pattern { get; private set; }
            public bool Match(HttpContext httpContext,
                              IRouter route,
                              string routeKey,
                              IDictionary<string, object> values,
                              RouteDirection routeDirection)
            {
                throw new NotImplementedException();
            }
        }

 使用的例子:

   var services = new ServiceCollection().AddOptions();
            services.Configure<RouteOptions>(options =>
                                options
                                .ConstraintMap
                                .Add("test", typeof(TestRouteConstraint)));
            var serviceProvider = services.BuildServiceProvider();
            var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
            return new DefaultInlineConstraintResolver(serviceProvider, accessor);