Beispiel #1
0
        internal HttpRoute(
            string routeTemplate,
            HttpRouteValueDictionary defaults,
            HttpRouteValueDictionary constraints,
            HttpRouteValueDictionary dataTokens,
            HttpMessageHandler handler,
            HttpParsedRoute parsedRoute
            )
        {
            _routeTemplate = routeTemplate == null ? String.Empty : routeTemplate;
            _defaults      = defaults ?? new HttpRouteValueDictionary();
            _constraints   = constraints ?? new HttpRouteValueDictionary();
            _dataTokens    = dataTokens ?? new HttpRouteValueDictionary();
            Handler        = handler;

            if (parsedRoute == null)
            {
                // The parser will throw for invalid routes.
                ParsedRoute = RouteParser.Parse(routeTemplate);
            }
            else
            {
                ParsedRoute = parsedRoute;
            }
        }
Beispiel #2
0
        /// <summary>Creates a route builder that can build a route matching this context.</summary>
        /// <param name="template">The route template.</param>
        /// <param name="constraintResolver">
        /// The inline constraint resolver to use, if any; otherwise, <see langword="null"/>.
        /// </param>
        /// <returns>A route builder that can build a route matching this context.</returns>
        public IDirectRouteBuilder CreateBuilder(string template, IInlineConstraintResolver constraintResolver)
        {
            DirectRouteBuilder builder = new DirectRouteBuilder(_actions, _targetIsAction);

#if ASPNETWEBAPI
            string prefixedTemplate = BuildRouteTemplate(_prefix, template);
#else
            string prefixedTemplate = BuildRouteTemplate(_areaPrefix, _controllerPrefix, template ?? String.Empty);
#endif
            ValidateTemplate(prefixedTemplate);

            if (constraintResolver != null)
            {
                TRouteDictionary defaults    = new TRouteDictionary();
                TRouteDictionary constraints = new TRouteDictionary();

                string detokenizedTemplate = InlineRouteTemplateParser.ParseRouteTemplate(prefixedTemplate, defaults,
                                                                                          constraints, constraintResolver);
                TParsedRoute parsedRoute = RouteParser.Parse(detokenizedTemplate);
                decimal      precedence  = RoutePrecedence.Compute(parsedRoute, constraints);

                builder.Defaults    = defaults;
                builder.Constraints = constraints;
                builder.Template    = detokenizedTemplate;
                builder.Precedence  = precedence;
                builder.ParsedRoute = parsedRoute;
            }
            else
            {
                builder.Template = prefixedTemplate;
            }

            return(builder);
        }
        public void TestExpectedBehavior()
        {
            var tokenizer = new RouteTokenizer();
            var parser = new RouteParser();

            var route = "/the/path/{to}/*/{glory}";
            var token = tokenizer.Tokenize(route);

            var routeInformation = parser.Parse(route, token);

            Assert.AreEqual(2, routeInformation.Parameter.Length);

            Assert.AreEqual("to", routeInformation.Parameter[0]);
            Assert.AreEqual("glory", routeInformation.Parameter[1]);

            Assert.AreEqual("the", routeInformation.Segments[0].Name);
            Assert.AreEqual(RouteSegmentType.Static, routeInformation.Segments[0].Type);
            Assert.AreEqual("path", routeInformation.Segments[1].Name);
            Assert.AreEqual(RouteSegmentType.Static, routeInformation.Segments[1].Type);
            Assert.AreEqual("to", routeInformation.Segments[2].Name);
            Assert.AreEqual(RouteSegmentType.Parameter, routeInformation.Segments[2].Type);
            Assert.AreEqual("*", routeInformation.Segments[3].Name);
            Assert.AreEqual(RouteSegmentType.Wildcard, routeInformation.Segments[3].Type);
            Assert.AreEqual("glory", routeInformation.Segments[4].Name);
            Assert.AreEqual(RouteSegmentType.Parameter, routeInformation.Segments[4].Type);
        }
Beispiel #4
0
 internal ParsedRoute ToParsedRoute()
 {
     if (parsedRoute == null)
     {
         parsedRoute = RouteParser.Parse(GetRouteUrl());
     }
     return(parsedRoute);
 }
Beispiel #5
0
        public void ParseParameterRouteTest()
        {
            var route = RouteParser.Parse("api/customers/{id}");

            Assert.AreEqual(3, route.Count);
            Assert.IsInstanceOf <LiteralRouteItem>(route[0]);
            Assert.IsInstanceOf <LiteralRouteItem>(route[1]);
            Assert.IsInstanceOf <ParameterRouteItem>(route[2]);
        }
Beispiel #6
0
        public void Parse_RouteWithOneRequiredAndOneOptinalInTheWrongOrder()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter? path", out commandName);
        }
Beispiel #7
0
        public void Parse_EmptyRoute()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("", out commandName);
        }
Beispiel #8
0
        public void Parse_NullRoute()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse(null, out commandName);
        }
Beispiel #9
0
        public void Parse_NullRoute()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse(null, out commandName);
        }
Beispiel #10
0
        public void Parse_EmptyRoute()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("", out commandName);
        }
Beispiel #11
0
        public void ParseParameterRouteItemAtMiddlePositionTest()
        {
            var route = RouteParser.Parse("api/customers/{id}/orders");

            Assert.AreEqual(4, route.Count);
            Assert.IsInstanceOf <LiteralRouteItem>(route[0]);
            Assert.IsInstanceOf <LiteralRouteItem>(route[1]);
            Assert.IsInstanceOf <ParameterRouteItem>(route[2]);
            Assert.IsInstanceOf <LiteralRouteItem>(route[3]);
        }
        private void PopulateActionDescriptions(HttpActionDescriptor actionDescriptor, IHttpRoute route, string localPath, Collection <ApiDescription> apiDescriptions)
        {
            string apiDocumentation = GetApiDocumentation(actionDescriptor);

            HttpParsedRoute parsedRoute = RouteParser.Parse(localPath);

            // parameters
            IList <ApiParameterDescription> parameterDescriptions = CreateParameterDescriptions(actionDescriptor, parsedRoute, route.Defaults);

            // expand all parameter variables
            string finalPath;

            if (!TryExpandUriParameters(route, parsedRoute, parameterDescriptions, out finalPath))
            {
                // the action cannot be reached due to parameter mismatch, e.g. routeTemplate = "/users/{name}" and GetUsers(id)
                return;
            }

            // request formatters
            ApiParameterDescription          bodyParameter = parameterDescriptions.FirstOrDefault(description => description.Source == ApiParameterSource.FromBody);
            IEnumerable <MediaTypeFormatter> supportedRequestBodyFormatters = bodyParameter != null?
                                                                              actionDescriptor.Configuration.Formatters.Where(f => f.CanReadType(bodyParameter.ParameterDescriptor.ParameterType)) :
                                                                                  Enumerable.Empty <MediaTypeFormatter>();

            // response formatters
            ResponseDescription responseDescription = CreateResponseDescription(actionDescriptor);
            Type returnType = responseDescription.ResponseType ?? responseDescription.DeclaredType;
            IEnumerable <MediaTypeFormatter> supportedResponseFormatters = (returnType != null && returnType != typeof(void)) ?
                                                                           actionDescriptor.Configuration.Formatters.Where(f => f.CanWriteType(returnType)) :
                                                                           Enumerable.Empty <MediaTypeFormatter>();

            // Replacing the formatter tracers with formatters if tracers are present.
            supportedRequestBodyFormatters = GetInnerFormatters(supportedRequestBodyFormatters);
            supportedResponseFormatters    = GetInnerFormatters(supportedResponseFormatters);

            // get HttpMethods supported by an action. Usually there is one HttpMethod per action but we allow multiple of them per action as well.
            IList <HttpMethod> supportedMethods = GetHttpMethodsSupportedByAction(route, actionDescriptor);

            foreach (HttpMethod method in supportedMethods)
            {
                apiDescriptions.Add(new ApiDescription
                {
                    Documentation                  = apiDocumentation,
                    HttpMethod                     = method,
                    RelativePath                   = finalPath,
                    ActionDescriptor               = actionDescriptor,
                    Route                          = route,
                    SupportedResponseFormatters    = new Collection <MediaTypeFormatter>(supportedResponseFormatters.ToList()),
                    SupportedRequestBodyFormatters = new Collection <MediaTypeFormatter>(supportedRequestBodyFormatters.ToList()),
                    ParameterDescriptions          = new Collection <ApiParameterDescription>(parameterDescriptions),
                    ResponseDescription            = responseDescription
                });
            }
        }
Beispiel #13
0
        private static RouteEntry CreateRouteEntry(string routeTemplate)
        {
            var route = new RouteBuilder().BuildDirectRoute(routeTemplate, new[] { "GET" }, "Controller", "Action", null, null);

            return(new RouteEntry()
            {
                Route = route,
                RouteTemplate = routeTemplate,
                ParsedRoute = RouteParser.Parse(route.Url)
            });
        }
Beispiel #14
0
        public void Parse_CanParseSimpleRouteWithTrailingSpace()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            parser.Parse("ls  ", out commandName);

            // Assert
            Assert.AreEqual("ls", commandName);
        }
        public void TestSlashInParameter()
        {
            var tokenizer = new RouteTokenizer();
            var parser = new RouteParser();

            var route = "/malformed/{rou/te}";
            var token = tokenizer.Tokenize(route);

            Assert.Throws<RouteParsingException>(() => {
                parser.Parse(route, token);
            });
        }
Beispiel #16
0
        public void Parse_CanParseSimpleRouteWithTrailingSpace()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            parser.Parse("ls  ", out commandName);

            // Assert
            Assert.AreEqual("ls", commandName);
        }
Beispiel #17
0
        public void Parse_RouteWithSingleOptionalParameter()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter?", out commandName);

            // Assert
            Assert.AreEqual(1, param.Count);
            Assert.AreEqual("filter", param.First().Key);
            Assert.AreEqual(ParameterType.Optional, param.First().Value);
        }
Beispiel #18
0
        public void Parse_RouteWithSingleOptionalParameter()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter?", out commandName);

            // Assert
            Assert.AreEqual(1, param.Count);
            Assert.AreEqual("filter", param.First().Key);
            Assert.AreEqual(ParameterType.Optional, param.First().Value);
        }
Beispiel #19
0
        private static decimal Compute(string template)
        {
            DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver();

#if ASPNETWEBAPI
            HttpRouteValueDictionary defaults    = new HttpRouteValueDictionary();
            HttpRouteValueDictionary constraints = new HttpRouteValueDictionary();
#else
            RouteValueDictionary defaults    = new RouteValueDictionary();
            RouteValueDictionary constraints = new RouteValueDictionary();
#endif
            string standardRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(template,
                                                                                        defaults, constraints, new DefaultInlineConstraintResolver());
            var parsedRoute = RouteParser.Parse(standardRouteTemplate);
            return(RoutePrecedence.Compute(parsedRoute, constraints));
        }
Beispiel #20
0
        private void Test()
        {
            IHeader header = _parser.Parse("Route",
                                           new StringReader(
                                               "<sip:bigbox3.site3.atlanta.com;lr>,\r\n <sip:server10.biloxi.com)"));

            Assert.IsType(typeof(Route), header);
            var route = (Route)header;

            Assert.Equal("bigbox3.site3.atlanta.com", route.Items[0].Uri.Domain);
            Assert.Equal("sip", route.Items[0].Uri.Scheme);
            Assert.True(route.Items[0].IsLoose);
            Assert.Equal("server10.biloxi.com", route.Items[1].Uri.Domain);
            Assert.Equal("sip", route.Items[1].Uri.Scheme);
            Assert.False(route.Items[1].IsLoose);
        }
Beispiel #21
0
        private void Awake()
        {
            var regex = RouteParser.Parse(_path, _exact);

            _route = new Route(_path, regex);

            var router = this.FindRouter();

            if (router == null)
            {
                throw new Exception("No RouterComponent found in parents");
            }

            router.OnLocationChanged += OnLocationChanged;

            OnLocationChanged(router.CurrentLocation);
        }
Beispiel #22
0
        public void Parse_RouteWithTwoOptionalParameters()
        {
            // Arrange
            var parser      = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter? path?", out commandName);

            // Assert
            Assert.AreEqual(2, param.Count);

            Assert.AreEqual("filter", param.First().Key);
            Assert.AreEqual(ParameterType.Optional, param.First().Value);

            Assert.AreEqual("path", param.Skip(1).Take(1).Single().Key);
            Assert.AreEqual(ParameterType.Optional, param.Skip(1).Take(1).Single().Value);
        }
Beispiel #23
0
        internal HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler, HttpParsedRoute parsedRoute)
        {
            _routeTemplate = routeTemplate == null ? String.Empty : routeTemplate;
            _defaults      = defaults ?? new HttpRouteValueDictionary();
            _constraints   = constraints ?? new HttpRouteValueDictionary();
            _dataTokens    = dataTokens ?? new HttpRouteValueDictionary();
            Handler        = handler;

            if (parsedRoute == null)
            {
                // The parser will throw for invalid routes.
                ParsedRoute = RouteParser.Parse(routeTemplate);
            }
            else
            {
                ParsedRoute = parsedRoute;
            }

            System.Diagnostics.Trace.WriteLine(string.Format("RouteTemplate:{0},HttpMessageHandler:{1}", this.RouteTemplate, this.Handler));
        }
Beispiel #24
0
        private void RegisterControllerType(Type controllerType)
        {
            string routePrefix = string.Empty;

            if (controllerType.IsDefined(typeof(RoutePrefixAttribute)))
            {
                routePrefix = (controllerType.GetCustomAttributes(typeof(RoutePrefixAttribute), false).First() as RoutePrefixAttribute).Prefix;
            }

            var methodQuery = from m in controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                              where m.IsDefined(typeof(HttpMethodAttribute), true)
                              select new
            {
                Route      = m.IsDefined(typeof(RouteAttribute)) ? m.GetCustomAttribute <RouteAttribute>().Name : m.Name,
                MethodInfo = m
            };

            foreach (var methodQueryItem in methodQuery)
            {
                string routeString = string.Empty;
                Route  route;
                if (methodQueryItem.Route.StartsWith("!"))
                {
                    routeString = methodQueryItem.Route.Substring(1);
                }
                else
                {
                    routeString = routePrefix;
                    if (!string.IsNullOrEmpty(routeString) && !routeString.EndsWith("/"))
                    {
                        routeString += "/";
                    }
                    routeString += methodQueryItem.Route;
                }
                try
                {
                    route = RouteParser.Parse(routeString);
                }
                catch (RouteParseException rpe)
                {
                    log.Warn(string.Format("Route parsing failed, ignoring the decorated controller method. (Route: \"{0}\", Method:{1}.{2})",
                                           routeString,
                                           controllerType.Name,
                                           methodQueryItem.MethodInfo.Name), rpe);

                    continue;
                }

                this.controllerRegistrations.Add(new ControllerRegistration
                {
                    ControllerMethod = methodQueryItem.MethodInfo,
                    ControllerType   = controllerType,
                    Route            = route,
                    RouteTemplate    = routeString
                });

                if (controllerType.IsDefined(typeof(SynchronizedAttribute)) && !synchronizedControllers.ContainsKey(controllerType.AssemblyQualifiedName))
                {
                    synchronizedControllers.Add(controllerType.AssemblyQualifiedName, (RaspkateController)Activator.CreateInstance(controllerType));
                }

                log.DebugFormat("Route \"{0}\" registered for controller method {1}.{2}.", routeString, controllerType.Name, methodQueryItem.MethodInfo.Name);
            }
        }
Beispiel #25
0
        /// <inheritdoc/>
        public virtual RouteEntry Build()
        {
            if (ParsedRoute == null)
            {
                ParsedRoute = RouteParser.Parse(Template);
            }

            ValidateParameters(ParsedRoute);

            TRouteDictionaryConcrete defaults;

#if ASPNETWEBAPI
            defaults = Copy(Defaults);
#else
            defaults = Copy(Defaults) ?? new RouteValueDictionary();
#endif
            TRouteDictionaryConcrete constraints = Copy(Constraints);
            TRouteDictionaryConcrete dataTokens  =
                Copy(DataTokens) ?? new TRouteDictionaryConcrete();

            dataTokens[RouteDataTokenKeys.Actions] = _actions;

#if ASPNETWEBAPI
            if (!TargetIsAction)
            {
                dataTokens[RouteDataTokenKeys.Controller] = _actions[0].ControllerDescriptor;
            }
#endif

            int order = Order;

            if (order != default(int))
            {
                dataTokens[RouteDataTokenKeys.Order] = order;
            }

            decimal precedence = Precedence;

            if (precedence != default(decimal))
            {
                dataTokens[RouteDataTokenKeys.Precedence] = precedence;
            }

#if ASPNETWEBAPI
            if (constraints != null)
            {
                foreach (var constraint in constraints)
                {
                    HttpRoute.ValidateConstraint(Template, constraint.Key, constraint.Value);
                }
            }

            HttpMessageHandler handler = null;
            IHttpRoute         route   = new HttpRoute(
                Template,
                defaults,
                constraints,
                dataTokens,
                handler,
                ParsedRoute
                );
#else
            ControllerDescriptor controllerDescriptor = GetControllerDescriptor();

            if (controllerDescriptor != null)
            {
                defaults["controller"] = controllerDescriptor.ControllerName;
            }

            if (TargetIsAction && _actions.Length == 1)
            {
                ActionDescriptor actionDescriptor = _actions[0];
                defaults["action"] = actionDescriptor.ActionName;

                dataTokens[RouteDataTokenKeys.TargetIsAction] = true;
            }

            RouteAreaAttribute area     = controllerDescriptor.GetAreaFrom();
            string             areaName = controllerDescriptor.GetAreaName(area);

            if (areaName != null)
            {
                dataTokens[RouteDataTokenKeys.Area] = areaName;
                dataTokens[RouteDataTokenKeys.UseNamespaceFallback] = false;

                Type controllerType = controllerDescriptor.ControllerType;

                if (controllerType != null)
                {
                    dataTokens[RouteDataTokenKeys.Namespaces] = new[] { controllerType.Namespace };
                }
            }

            Route route = new Route(
                Template,
                defaults,
                constraints,
                dataTokens,
                routeHandler: null
                );

            ConstraintValidation.Validate(route);
#endif

            return(new RouteEntry(Name, route));
        }
Beispiel #26
0
        public void Parse_RouteWithTwoOptionalParameters()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter? path?", out commandName);

            // Assert
            Assert.AreEqual(2, param.Count);
            
            Assert.AreEqual("filter", param.First().Key);
            Assert.AreEqual(ParameterType.Optional, param.First().Value);

            Assert.AreEqual("path", param.Skip(1).Take(1).Single().Key);
            Assert.AreEqual(ParameterType.Optional, param.Skip(1).Take(1).Single().Value);
        }
Beispiel #27
0
        public void Parse_RouteWithOneRequiredAndOneOptinalInTheWrongOrder()
        {
            // Arrange
            var parser = new RouteParser();
            var commandName = "";

            // Act
            var param = parser.Parse("ls filter? path", out commandName);
        }