导航

09-003 Routing 之 InlineRouteParameterParser

Posted on 2015-04-07 16:23  DotNet1010  阅读(138)  评论(0)    收藏  举报

先看一下三个正则表达式:

        // One or more characters, matches "id"
        private const string ParameterNamePattern = @"(?<parameterName>.+?)";

        // Zero or more inline constraints that start with a colon followed by zero or more characters
        // Optionally the constraint can have arguments within parentheses
        //      - necessary to capture characters like ":" and "}"
        // Matches ":int", ":length(2)", ":regex(\})", ":regex(:)" zero or more times
        private const string ConstraintPattern = @"(:(?<constraint>.*?(\(.*?\))?))*";

        // A default value with an equal sign followed by zero or more characters
        // Matches "=", "=abc"
        private const string DefaultValueParameter = @"(?<defaultValue>(=.*?))?";

 完整的匹配上上述三部分 参数 约束 默认值 的相加:

        private static readonly Regex _parameterRegex = new Regex(
           "^" + ParameterNamePattern + ConstraintPattern + DefaultValueParameter + "$",
            RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

 看一下核心代码:

	//举例: {id:int:max(100):min(50)=60}
		public static TemplatePart ParseRouteParameter([NotNull] string routeParameter)
		{
			// 以 *  符号开始
			var isCatchAll = routeParameter.StartsWith("*", StringComparison.Ordinal);
			// 以 ? 符号结束 每一个Segment只能有一个可选参数 且必须是最后一个参数
			var isOptional = routeParameter.EndsWith("?", StringComparison.Ordinal);

			routeParameter = isCatchAll ? routeParameter.Substring(1) : routeParameter;
			routeParameter = isOptional ? routeParameter.Substring(0, routeParameter.Length - 1) : routeParameter;

			var parameterMatch = _parameterRegex.Match(routeParameter);
			if (!parameterMatch.Success)
			{
				return TemplatePart.CreateParameter(name: string.Empty,
													isCatchAll: isCatchAll,
													isOptional: isOptional,
													defaultValue: null,
													inlineConstraints: null);
			}

			// 以 {id:int:max(100):min(50)=60} 为例 parameterName="id";
			var parameterName = parameterMatch.Groups["parameterName"].Value;

			// Add the default value if present
			// 以 {id:int:max(100):min(50)=60} 为例 parameterName="id";
			//  defaultValueGroup 是 =60
			//  defaultValue   是 60 去掉了 = 符号
			var defaultValueGroup = parameterMatch.Groups["defaultValue"];
			var defaultValue = GetDefaultValue(defaultValueGroup);

			// Register inline constraints if present
			// 这里是三个   int     max(100)    min(50)  不包含冒号
			var constraintGroup = parameterMatch.Groups["constraint"];
			var inlineConstraints = GetInlineConstraints(constraintGroup);

			return TemplatePart.CreateParameter(parameterName,
												isCatchAll,
												isOptional,
												defaultValue,
												inlineConstraints);
		}