public RouteFromParametersTests()
 {
     var conventions = new RoutingConventions();
     _sut = new RouteFromParametersConvention();
     var routes = _sut.Build(new RouteBuilderInfo(new ActionCall(typeof(MyController).GetMethod("GetSomething")), conventions));
     _route = routes.First();
 }
        /// <inheritdoc />
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (route == null)
            {
                throw Error.ArgumentNull("route");
            }

            if (parameterName == null)
            {
                throw Error.ArgumentNull("parameterName");
            }

            if (values == null)
            {
                throw Error.ArgumentNull("values");
            }

            // If the parameter is optional and has no value, then pass the constraint
            object defaultValue;
            if (route.Defaults.TryGetValue(parameterName, out defaultValue) && defaultValue == RouteParameter.Optional)
            {
                object value;
                if (values.TryGetValue(parameterName, out value) && value == RouteParameter.Optional)
                {
                    return true;
                }
            }

            return InnerConstraint.Match(request, route, parameterName, values, routeDirection);
        }
        public override bool Match(
            HttpRequestMessage request,
            IHttpRoute route,
            string parameterName,
            IDictionary<string, object> values,
            HttpRouteDirection routeDirection)
        {
            foreach (string key in HeaderConstraints.Keys)
            {
                if (!request.Headers.Contains(key)
                    || string.Compare(request.Headers.GetValues(key).FirstOrDefault(), HeaderConstraints[key].ToString(), true) != 0)
                {
                    return false;
                }
            }

            var queries = request.GetQueryNameValuePairs().ToDictionary(p => p.Key, p => p.Value);
            foreach (var key in QueryStringConstraints.Keys)
            {
                if (!queries.ContainsKey(key)
                    || string.Compare(queries[key], QueryStringConstraints[key].ToString(), true) != 0)
                {
                    return false;
                }
            }

            return base.Match(request, route, parameterName, values, routeDirection);
        }
        protected override bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (routeDirection == HttpRouteDirection.UriGeneration)
                return true;

            return base.Match(request, route, parameterName, values, routeDirection);
        }
        private void ExploreRouteControllers(IDictionary<string, HttpControllerDescriptor> controllerMappings, IHttpRoute route, Collection<ApiDescription> apiDescriptions)
        {
            string routeTemplate = route.RouteTemplate;
            object controllerVariableValue;
            if (_controllerVariableRegex.IsMatch(routeTemplate))
            {
                // unbound controller variable, {controller}
                foreach (KeyValuePair<string, HttpControllerDescriptor> controllerMapping in controllerMappings)
                {
                    controllerVariableValue = controllerMapping.Key;
                    HttpControllerDescriptor controllerDescriptor = controllerMapping.Value;

                    if (DefaultExplorer.ShouldExploreController(controllerVariableValue.ToString(), controllerDescriptor, route))
                    {
                        // expand {controller} variable
                        string expandedRouteTemplate = _controllerVariableRegex.Replace(routeTemplate, controllerVariableValue.ToString());
                        ExploreRouteActions(route, expandedRouteTemplate, controllerDescriptor, apiDescriptions);
                    }
                }
            }
            else
            {
                // bound controller variable, {controller = "controllerName"}
                if (route.Defaults.TryGetValue(ControllerVariableName, out controllerVariableValue))
                {
                    HttpControllerDescriptor controllerDescriptor;
                    if (controllerMappings.TryGetValue(controllerVariableValue.ToString(), out controllerDescriptor) && DefaultExplorer.ShouldExploreController(controllerVariableValue.ToString(), controllerDescriptor, route))
                    {
                        ExploreRouteActions(route, routeTemplate, controllerDescriptor, apiDescriptions);
                    }
                }
            }
        }
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            object rawValue;

             if (!values.TryGetValue(parameterName, out rawValue)
            || rawValue == null) {

            return true;
             }

             if (this.ParameterType.IsInstanceOfType(rawValue)) {
            return true;
             }

             string attemptedValue = Convert.ToString(rawValue, CultureInfo.InvariantCulture);

             if (attemptedValue.Length == 0) {
            return true;
             }

             object parsedVal;

             if (!TryParse(request, parameterName, rawValue, attemptedValue, CultureInfo.InvariantCulture, out parsedVal)) {
            return false;
             }

             if (routeDirection == HttpRouteDirection.UriResolution) {
            values[parameterName] = parsedVal;
             }

             return true;
        }
Пример #7
0
        public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (values == null) // shouldn't ever hit this.
                return true;

            if (!values.ContainsKey(parameterName) || !values.ContainsKey(_id)) // make sure the parameter is there.
                return true;

            var action = values[parameterName].ToString().ToLower();
            if (string.IsNullOrEmpty(action)) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
            {
                values[parameterName] = request.Method.ToString();
            }
            else if (string.IsNullOrEmpty(values[_id].ToString()))
            {
                var isidstr = true;
                array.ToList().ForEach(x =>
                {
                    if (action.StartsWith(x.ToLower()))
                        isidstr = false;
                });

                if (isidstr)
                {
                    values[_id] = values[parameterName];
                    values[parameterName] = request.Method.ToString();
                }
            }
            return true;
        }
        public bool TryAddRoute(string routeName, string routeTemplate, IEnumerable<HttpMethod> methods, HttpRouteCollection routes, out IHttpRoute route)
        {
            route = null;

            try
            {
                var routeBuilder = CreateRouteBuilder(routeTemplate);
                var constraints = routeBuilder.Constraints;
                if (methods != null)
                {
                    // if the methods collection is not null, apply the constraint
                    // if the methods collection is empty, we'll create a constraint
                    // that disallows ALL methods
                    constraints.Add("httpMethod", new HttpMethodConstraint(methods.ToArray()));
                }
                route = routes.CreateRoute(routeBuilder.Template, routeBuilder.Defaults, constraints);
                routes.Add(routeName, route);
            }
            catch (Exception ex) when (!ex.IsFatal()) 
            {
                // catch any route parsing errors
                return false;
            }

            return true;
        }
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
     IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     var versionFinder = new VersionFinder();
     var version = versionFinder.GetVersionFromRequest(request);
     return _version == version;
 }
Пример #10
0
        /// <inheritdoc />
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
            IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            // The match behaviour depends on value of IsRelaxedMatch.
            // If users select using relaxed match logic, the header contains both V3 (or before) and V4 style version
            // will be regarded as valid. While under non-relaxed match logic, both version headers presented will be
            // regarded as invalid. The behavior for other situations are the same. When non version headers present,
            // assume using MaxVersion.

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (routeDirection == HttpRouteDirection.UriGeneration)
            {
                return true;
            }

            if (!ValidateVersionHeaders(request))
            {
                return false;
            }

            ODataVersion? requestVersion = GetVersion(request);
            return requestVersion.HasValue && requestVersion.Value >= MinVersion && requestVersion.Value <= MaxVersion;
        }
Пример #11
0
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
     IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     if (values == null)
     {
         return true;
     }
     if (!values.ContainsKey(parameterName) || !values.ContainsKey(Id))
     {
         return true;
     }
     string action = values[parameterName].ToString().ToLower();
     if (string.IsNullOrEmpty(action))
     {
         values[parameterName] = request.Method.ToString();
     }
     else if (string.IsNullOrEmpty(values[Id].ToString()))
     {
         bool isAction = _array.All(item => action.StartsWith(item.ToLower()));
         if (isAction)
         {
             return true;
         }
         //values[Id] = values[parameterName];
         //values[parameterName] = request.Method.ToString();
     }
     return true;
 }
Пример #12
0
 public bool Match(
     HttpRequestMessage request,
     IHttpRoute route,
     string parameterName,
     IDictionary<string, object> values,
     HttpRouteDirection routeDirection) =>
         Match(parameterName, values);
        /// <inheritdoc />
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (parameterName == null)
            {
                throw Error.ArgumentNull("parameterName");
            }

            if (values == null)
            {
                throw Error.ArgumentNull("values");
            }

            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                int length = valueString.Length;
                if (Length.HasValue)
                {
                    return length == Length.Value;
                }
                else
                {
                    return length >= MinLength.Value && length <= MaxLength.Value;
                }
            }
            return false;
        }
Пример #14
0
 public InitController(String controllerName)
 {
     this.config = new HttpConfiguration();
     this.request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/"+controllerName+"Controller");
     this.route = config.Routes.MapHttpRoute(controllerName, "api/{controller}/{id}");
     this.routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", controllerName } });
 }
        /// <inheritdoc />
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (parameterName == null)
            {
                throw Error.ArgumentNull("parameterName");
            }

            if (values == null)
            {
                throw Error.ArgumentNull("values");
            }

            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                if (value is long)
                {
                    return true;
                }

                long result;
                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                return Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
            }
            return false;
        }
        public bool Match(HttpRequestMessage request,
                          IHttpRoute route,
                          string segmentPrefix,
                          IDictionary<string, object> values,
                          HttpRouteDirection routeDirection)
        {
            if (segmentPrefix == null)
            {
                throw new ArgumentNullException("segmentPrefix");
            }

            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            object value;
            if (values.TryGetValue(segmentPrefix, out value))
            {
                string valueString = value as string;
                return valueString != null
                       && (valueString.StartsWith(segmentPrefix + ";", StringComparison.OrdinalIgnoreCase)
                           || String.Equals(valueString, segmentPrefix, StringComparison.OrdinalIgnoreCase));
            }
            return false;
        }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedirectRouteHandler"/> class.
        /// </summary>
        /// <param name="target">
        /// The target route.
        /// </param>
        /// <param name="permanently">
        /// if set to <c>true</c>, the route has permanently been redirected.
        /// </param>
        public RedirectRouteHandler(IHttpRoute target, bool permanently)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            this.target = target;
            this.permanently = permanently;
        }
Пример #18
0
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
     HttpRouteDirection routeDirection)
 {
     return request.Headers.UserAgent
         .Where(ua => ua.Product != null)
         .Where(ua => ua.Product.Name != null)
         .Any(ua => ua.Product.Name.IndexOf("NuGet", StringComparison.InvariantCultureIgnoreCase) != -1);
 }
Пример #19
0
 public bool Match(HttpRequestMessage request,
     IHttpRoute route,
     string parameterName,
     IDictionary<string, object> values,
     HttpRouteDirection routeDirection)
 {
     return request.Method == Method;
 }
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     object culture;
     if (values.TryGetValue(parameterName, out culture))
     {
         return allCultures.Any(c => string.Compare(c, culture.ToString(), true) == 0);
     }
     return false;
 }
 public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     object value = null;
     if (values.TryGetValue(parameterName, out value))
     {
         return value == RouteParameter.Optional;
     }
     return true;
 }
Пример #22
0
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (routeDirection == HttpRouteDirection.UriResolution)
            {
                return IsRequiredHeaderPresent(request);
            }

            return false;
        }
Пример #23
0
        public LinkGenerationRoute(IHttpRoute innerRoute)
        {
            if (innerRoute == null)
            {
                throw new ArgumentNullException("innerRoute");
            }

            _innerRoute = innerRoute;
        }
        public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (routeDirection == HttpRouteDirection.UriResolution)
            {
                return true;
            }

            return false;
        }
 public bool Match(
     HttpRequestMessage request,
     IHttpRoute route,
     string parameterName,
     IDictionary<string, object> values,
     HttpRouteDirection routeDirection)
 {
     return routeDirection == _allowedDirection;
 }
 /// <summary>
 /// Determines whether this instance equals a specified route.
 /// </summary>
 /// <returns>
 /// True if this instance equals a specified route; otherwise, false.
 /// </returns>
 /// <param name="request">The request.</param><param name="route">The route to compare.</param><param name="parameterName">The name of the parameter.</param><param name="values">A list of parameter values.</param><param name="routeDirection">The route direction.</param>
 public bool Match(
     HttpRequestMessage request,
     IHttpRoute route,
     string parameterName,
     IDictionary<string, object> values,
     HttpRouteDirection routeDirection)
 {
     return ((IHttpRouteConstraint) selfHostConstraint).Match(request, route, parameterName, values, routeDirection);
 }
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     object value;
     if (values.TryGetValue(parameterName, out value) && value != null)
     {
         return AllowedVersion.Equals(value.ToString().ToLowerInvariant());
     }
     return false;
 }
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (routeDirection != HttpRouteDirection.UriResolution)
                return true;

            var version = GetVersionHeader(request) ?? DefaultVersion;

            return (version == AllowedVersion);
        }
        public HostedHttpVirtualPathData(VirtualPathData virtualPath, IHttpRoute httpRoute)
        {
            if (virtualPath == null)
            {
                throw Error.ArgumentNull("route");
            }

            _virtualPath = virtualPath;
            Route = httpRoute;
        }
Пример #30
0
        public HttpWebRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler, IHttpRoute httpRoute)
            : base(url, defaults, constraints, dataTokens, routeHandler)
        {
            if (httpRoute == null)
            {
                throw Error.ArgumentNull("httpRoute");
            }

            HttpRoute = httpRoute;
        }
Пример #31
0
        public void MapODataServiceRoute_ConfiguresARoute_RelexVersionConstraints()
        {
            // Arrange
            HttpRouteCollection routes = new HttpRouteCollection();
            HttpConfiguration   config = new HttpConfiguration(routes);
            IEdmModel           model  = new EdmModel();
            string routeName           = "name";
            string routePrefix         = "prefix";

            // Act
            config.Routes.MapODataServiceRoute(routeName, routePrefix, model);

            // Assert
            IHttpRoute odataRoute             = routes[routeName];
            var        odataVersionConstraint = Assert.Single(odataRoute.Constraints.Values.OfType <ODataVersionConstraint>());

            Assert.Equal(true, odataVersionConstraint.IsRelaxedMatch);
        }
Пример #32
0
        public void MapODataServiceRoute_AddsBatchRoute_WhenBatchHandlerIsProvided()
        {
            HttpRouteCollection routes = new HttpRouteCollection();
            HttpConfiguration   config = new HttpConfiguration(routes);
            IEdmModel           model  = new EdmModel();
            string routeName           = "name";
            string routePrefix         = "prefix";

            var batchHandler = new DefaultODataBatchHandler(new HttpServer());

            config.MapODataServiceRoute(routeName, routePrefix, model, batchHandler);

            IHttpRoute batchRoute = routes["nameBatch"];

            Assert.NotNull(batchRoute);
            Assert.Same(batchHandler, batchRoute.Handler);
            Assert.Equal("prefix/$batch", batchRoute.RouteTemplate);
        }
Пример #33
0
        public void MapHttpRoute1WithDefaultsAsDictionaryCreatesRoute()
        {
            // Arrange
            HttpRouteCollection routes = new HttpRouteCollection();
            object defaults            = new Dictionary <string, object> {
                { "d1", "D1" }
            };

            // Act
            IHttpRoute route = routes.MapHttpRoute("name", "template", defaults);

            // Assert
            Assert.NotNull(route);
            Assert.Equal("template", route.RouteTemplate);
            Assert.Equal(1, route.Defaults.Count);
            Assert.Equal("D1", route.Defaults["d1"]);
            Assert.Same(route, routes["name"]);
        }
Пример #34
0
      public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) {

         object rawValue;

         if (!values.TryGetValue(parameterName, out rawValue)
            || rawValue == null) {

            return true;
         }

         string attemptedValue = Convert.ToString(rawValue, CultureInfo.InvariantCulture);

         if (attemptedValue.Length == 0) {
            return true;
         }

         return this.set.Contains(attemptedValue);
      }
Пример #35
0
        public static string GetAreaName(this IHttpRoute route)
        {
            var routeWithArea = route as IRouteWithArea;

            if (routeWithArea != null)
            {
                return(routeWithArea.Area);
            }

            var castRoute = route as Route;

            if (castRoute != null && castRoute.DataTokens != null)
            {
                return(castRoute.DataTokens["area"] as string);
            }

            return(null);
        }
Пример #36
0
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="routeBuilder">The <see cref="HttpRouteBuilder"/> to use for generating attribute routes.</param>
        public static void MapHttpAttributeRoutes(this HttpConfiguration configuration, HttpRouteBuilder routeBuilder)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            if (routeBuilder == null)
            {
                throw Error.ArgumentNull("routeBuilder");
            }

            List <HttpRouteEntry> attributeRoutes = new List <HttpRouteEntry>();

            IHttpControllerSelector controllerSelector = configuration.Services.GetHttpControllerSelector();
            IDictionary <string, HttpControllerDescriptor> controllerMap = controllerSelector.GetControllerMapping();

            if (controllerMap != null)
            {
                foreach (HttpControllerDescriptor controllerDescriptor in controllerMap.Values)
                {
                    IEnumerable <HttpRouteEntry> controllerRoutes = CreateRouteEntries(controllerDescriptor);

                    foreach (HttpRouteEntry route in controllerRoutes)
                    {
                        route.Route = routeBuilder.BuildHttpRoute(route.RouteTemplate, route.HttpMethods, route.Actions);
                    }

                    SetDefaultRouteNames(controllerRoutes, controllerDescriptor.ControllerName);
                    attributeRoutes.AddRange(controllerRoutes);
                }

                attributeRoutes.Sort();

                foreach (HttpRouteEntry attributeRoute in attributeRoutes)
                {
                    IHttpRoute route = attributeRoute.Route;
                    if (route != null)
                    {
                        configuration.Routes.Add(attributeRoute.Name, attributeRoute.Route);
                    }
                }
            }
        }
Пример #37
0
        void ExploreRouteActions(
            IHttpRoute route,
            HttpControllerDescriptor controllerDescriptor,
            IHttpActionSelector actionSelector,
            Collection <VersionedApiDescription> apiDescriptions,
            ApiVersion apiVersion)
        {
            var actionMapping = actionSelector.GetActionMapping(controllerDescriptor);

            if (actionMapping == null)
            {
                return;
            }

            foreach (var grouping in actionMapping)
            {
                foreach (var action in grouping)
                {
                    if (!ShouldExploreAction(actionRouteParameterValue: string.Empty, action, route, apiVersion))
                    {
                        continue;
                    }

                    var parameterDescriptions = CreateParameterDescriptions(action, route);
                    var context = new ODataRouteBuilderContext(
                        Configuration,
                        apiVersion,
                        (ODataRoute)route,
                        action,
                        parameterDescriptions,
                        ModelTypeBuilder,
                        Options);

                    if (context.IsRouteExcluded)
                    {
                        continue;
                    }

                    var relativePath = new ODataRouteBuilder(context).Build();

                    PopulateActionDescriptions(action, route, context, relativePath, apiDescriptions, apiVersion);
                }
            }
        }
Пример #38
0
        public bool Match
        (
            HttpRequestMessage request
            , IHttpRoute route
            , string parameterName
            , IDictionary <string, object> values
            , HttpRouteDirection routeDirection
        )
        {
            if (routeDirection != HttpRouteDirection.UriResolution)
            {
                return(true);
            }
            var version = GetSemanticVersion(request);
            //Instance = this;

            var constraints = route.Constraints;



            //var virtualPath= route.GetVirtualPath(request, values).VirtualPath;

            //var routeData = route.GetRouteData(virtualPath, request);


            //AllowedVersionRange.FindBestMatch()

            var cacheDictionary = SemanticVersionedRouteCacheManager
                                  .Cache;


            //cacheDictionary
            //    .TryGetValue
            //        (

            //        )


            var r = AllowedVersionRange.Satisfies(version);

            return
                //(version == AllowedVersion)
                (r);
        }
Пример #39
0
        public ElectionMonitoringController SetupControllerForTests(Mock <IRaceResultService> mockRaceResultRepo,
                                                                    Mock <IRegionRepository> mockRegionRepo,
                                                                    Mock <IRaceRepository> mockRaceRepo)
        {
            var controller = new ElectionMonitoringController(mockRaceResultRepo.Object, mockRegionRepo.Object,
                                                              mockRaceRepo.Object);
            var        config    = new HttpConfiguration();
            IHttpRoute route     = config.Routes.MapHttpRoute("ActionApi", "api/{controller}/{action}/{id}");
            var        routeData = new HttpRouteData(route, new HttpRouteValueDictionary {
                { "controller", "electionmonitoring" }
            });
            var request = new HttpRequestMessage();

            request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            controller.ControllerContext = new HttpControllerContext(config, routeData, request);
            controller.Request           = request;
            return(controller);
        }
Пример #40
0
        /// <summary>
        /// IHttpRouteConstraint.Match implementation to validate a parameter against
        /// the Enum members.  String comparison is NOT case-sensitive.
        /// </summary>
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
                          IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            object value;

            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                var stringVal = value as string;
                if (!String.IsNullOrEmpty(stringVal))
                {
                    if (IsValidAccount(stringVal))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        private static Exception CreateAmbiguousControllerException(IHttpRoute route, string controllerName, ICollection <Type> matchingTypes)
        {
            Contract.Assert(route != null);
            Contract.Assert(controllerName != null);
            Contract.Assert(matchingTypes != null);

            // Generate an exception containing all the controller types
            StringBuilder typeList = new StringBuilder();

            foreach (Type matchedType in matchingTypes)
            {
                typeList.AppendLine();
                typeList.Append(matchedType.FullName);
            }

            string errorMessage = string.Format("Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request ('{1}') found multiple controllers defined with the same name but differing namespaces, which is not supported.{3}{3}The request for '{0}' has found the following matching controllers:{2}", controllerName, route.RouteTemplate, typeList, Environment.NewLine);

            return(new InvalidOperationException(errorMessage));
        }
        public bool Match(
            HttpRequestMessage request,
            IHttpRoute route,
            string parameterName,
            IDictionary <string, object> values,
            HttpRouteDirection routeDirection)
        {
            if (values.TryGetValue(parameterName, out object routeValue))
            {
                string number = routeValue.ToString();

                return(peselValidator.IsValid(number));
            }

            else
            {
                return(false);
            }
        }
Пример #43
0
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            object value1;

            if (values.TryGetValue(parameterName, out value1) && value1 != null)
            {
                var stringVal = value1 as string;
                if (!string.IsNullOrEmpty(stringVal))
                {
                    stringVal = stringVal.ToLower();

                    if (null != _enum.GetEnumNames().FirstOrDefault(a => a.ToLower().Equals(stringVal)))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #44
0
        public void GetVirtualPath_MatchesHttpRoute(string odataPath)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/vpath/prefix/Customers");
            HttpConfiguration  config  = new HttpConfiguration(new HttpRouteCollection("http://localhost/vpath"));

            request.SetConfiguration(config);

            IHttpRoute httpRoute  = config.Routes.CreateRoute("prefix/{*odataPath}", defaults: null, constraints: null);
            ODataRoute odataRoute = new ODataRoute("prefix", pathConstraint: null);

            // Test that the link generated by ODataRoute matches the one generated by HttpRoute
            Assert.Equal(
                httpRoute.GetVirtualPath(request, new HttpRouteValueDictionary {
                { "odataPath", odataPath }, { "httproute", true }
            }).VirtualPath,
                odataRoute.GetVirtualPath(request, new HttpRouteValueDictionary {
                { "odataPath", odataPath }, { "httproute", true }
            }).VirtualPath);
        }
Пример #45
0
    //This method is as it is in the base class
    private static bool MatchRegexConstraint(IHttpRoute route, string parameterName, string parameterValue)
    {
        IDictionary <string, object> constraints = route.Constraints;

        if (constraints != null)
        {
            object constraint;
            if (constraints.TryGetValue(parameterName, out constraint))
            {
                string constraintsRule = constraint as string;
                if (constraintsRule != null)
                {
                    string constraintsRegEx = "^(" + constraintsRule + ")$";
                    return(parameterValue != null && Regex.IsMatch(parameterValue, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase));
                }
            }
        }
        return(true);
    }
        public bool Match(
            HttpRequestMessage request,
            IHttpRoute route,
            string parameterName,
            IDictionary <string, object> values,
            HttpRouteDirection routeDirection)
        {
            if (values[parameterName] != RouteParameter.Optional)
            {
                object value;
                values.TryGetValue(parameterName, out value);
                string input = Convert.ToString(value, CultureInfo.InvariantCulture);

                Guid guidValue;
                return(Guid.TryParseExact(input, _format, out guidValue));
            }

            return(true);
        }
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            var attributeRoute = (IAttributeRoute)route;
            var allDefaults    = new Dictionary <string, object>();

            allDefaults.Merge(attributeRoute.Defaults);
            allDefaults.Merge(attributeRoute.QueryStringDefaults);

            // If the param is optional and has no value, then pass the constraint
            if (allDefaults.ContainsKey(parameterName) && allDefaults[parameterName] == RouteParameter.Optional)
            {
                if (values[parameterName].HasNoValue())
                {
                    return(true);
                }
            }

            return(_constraint.Match(request, route, parameterName, values, routeDirection));
        }
Пример #48
0
        public static HttpControllerDescriptor GetTargetControllerDescriptor(this IHttpRoute route)
        {
            Contract.Assert(route != null);
            IDictionary <string, object> dataTokens = route.DataTokens;

            if (dataTokens == null)
            {
                return(null);
            }

            HttpControllerDescriptor controller;

            if (!dataTokens.TryGetValue <HttpControllerDescriptor>(RouteDataTokenKeys.Controller, out controller))
            {
                return(null);
            }

            return(controller);
        }
Пример #49
0
        public static HttpActionDescriptor[] GetTargetActionDescriptors(this IHttpRoute route)
        {
            Contract.Assert(route != null);
            IDictionary <string, object> dataTokens = route.DataTokens;

            if (dataTokens == null)
            {
                return(null);
            }

            HttpActionDescriptor[] actions;

            if (!dataTokens.TryGetValue <HttpActionDescriptor[]>(RouteDataTokenKeys.Actions, out actions))
            {
                return(null);
            }

            return(actions);
        }
Пример #50
0
        /// <summary>
        /// Determines whether the route constraint matches the specified criteria.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage">HTTP request</see>.</param>
        /// <param name="route">The current <see cref="IHttpRoute">route</see>.</param>
        /// <param name="parameterName">The parameter name to match.</param>
        /// <param name="values">The current <see cref="IDictionary{TKey, TValue}">collection</see> of route values.</param>
        /// <param name="routeDirection">The <see cref="HttpRouteDirection">route direction</see> to match.</param>
        /// <returns>True if the route constraint is matched; otherwise, false.</returns>
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            var value = default(string);

            if (routeDirection == UriGeneration)
            {
                return(!IsNullOrEmpty(parameterName) && values.TryGetValue(parameterName, out value) && !IsNullOrEmpty(value));
            }

            var requestedVersion = default(ApiVersion);

            if (!values.TryGetValue(parameterName, out value) || !TryParse(value, out requestedVersion))
            {
                return(false);
            }

            request.SetRequestedApiVersion(requestedVersion);
            return(true);
        }
Пример #51
0
        public bool Match(HttpRequestMessage request, IHttpRoute route,
                          string parameterName, IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            if (routeDirection == HttpRouteDirection.UriResolution)
            {
                // try custom header api-version
                int?version = GetVersionFromCustomRequestHeader(request);

                // not found? Try content type in accpet header
                if (version == null)
                {
                    version = GetVersionFromCustomContentType(request);
                }

                return(((version ?? defaultVersion)) == AllowedVersion);
            }

            return(true);
        }
Пример #52
0
        void PopulateActionDescriptions(HttpActionDescriptor actionDescriptor, IHttpRoute route, string localPath, Collection <VersionedApiDescription> apiDescriptions, ApiVersion apiVersion)
        {
            var parameterDescriptions = CreateParameterDescriptions(actionDescriptor, route);
            var context = new ODataRouteBuilderContext(Configuration, localPath, (ODataRoute)route, actionDescriptor, parameterDescriptions);

            if (context.EdmModel.EntityContainer == null)
            {
                return;
            }

            var relativePath        = new ODataRouteBuilder(context).Build();
            var documentation       = DocumentationProvider?.GetDocumentation(actionDescriptor);
            var responseDescription = CreateResponseDescription(actionDescriptor);
            var responseType        = responseDescription.ResponseType ?? responseDescription.DeclaredType;
            var requestFormatters   = new List <MediaTypeFormatter>();
            var responseFormatters  = new List <MediaTypeFormatter>();
            var supportedMethods    = GetHttpMethodsSupportedByAction(route, actionDescriptor);
            var deprecated          = actionDescriptor.ControllerDescriptor.GetApiVersionModel().DeprecatedApiVersions.Contains(apiVersion);

            PopulateMediaTypeFormatters(actionDescriptor, parameterDescriptions, route, responseType, requestFormatters, responseFormatters);

            foreach (var method in supportedMethods)
            {
                var apiDescription = new VersionedApiDescription()
                {
                    Documentation       = documentation,
                    HttpMethod          = method,
                    RelativePath        = relativePath,
                    ActionDescriptor    = actionDescriptor,
                    Route               = route,
                    ResponseDescription = responseDescription,
                    ApiVersion          = apiVersion,
                    IsDeprecated        = deprecated,
                    Properties          = { [typeof(IEdmModel)] = context.EdmModel },
                };

                apiDescription.ParameterDescriptions.AddRange(parameterDescriptions);
                apiDescription.SupportedRequestBodyFormatters.AddRange(requestFormatters);
                apiDescription.SupportedResponseFormatters.AddRange(responseFormatters);
                PopulateApiVersionParameters(apiDescription, apiVersion);
                apiDescriptions.Add(apiDescription);
            }
        }
        public void MapHttpRoute2CreatesRoute()
        {
            // Arrange
            HttpRouteCollection routes = new HttpRouteCollection();
            object defaults            = new { d1 = "D1" };
            object constraints         = new { c1 = "C1" };

            // Act
            IHttpRoute route = routes.MapHttpRoute("name", "template", defaults, constraints);

            // Assert
            Assert.NotNull(route);
            Assert.Equal("template", route.RouteTemplate);
            Assert.Equal(1, route.Defaults.Count);
            Assert.Equal("D1", route.Defaults["d1"]);
            Assert.Equal(1, route.Defaults.Count);
            Assert.Equal("C1", route.Constraints["c1"]);
            Assert.Same(route, routes["name"]);
        }
Пример #54
0
        private static Exception CreateAmbiguousControllerException(IHttpRoute route, string controllerName, ICollection <Type> matchingTypes)
        {
            Contract.Assert(route != null);
            Contract.Assert(controllerName != null);
            Contract.Assert(matchingTypes != null);

            // Generate an exception containing all the controller types
            StringBuilder typeList = new StringBuilder();

            foreach (Type matchedType in matchingTypes)
            {
                typeList.AppendLine();
                typeList.Append(matchedType.FullName);
            }

            string errorMessage = Error.Format(SRResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate, controllerName, route.RouteTemplate, typeList, Environment.NewLine);

            return(new InvalidOperationException(errorMessage));
        }
Пример #55
0
        /// <inheritdoc />
        /// <remarks>This signature uses types that are AspNet-specific.</remarks>
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
                          IDictionary <string, object> values, HttpRouteDirection routeDirection)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (routeDirection == HttpRouteDirection.UriGeneration)
            {
                return(true);
            }

            IDictionary <string, IEnumerable <string> > headers = request.Headers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            ODataVersion?serviceVersion    = request.ODataProperties().ODataServiceVersion;
            ODataVersion?maxServiceVersion = request.ODataProperties().ODataMaxServiceVersion;

            return(IsVersionMatch(headers, serviceVersion, maxServiceVersion));
        }
        private static Exception CreateAmbiguousControllerException(IHttpRoute route, string controllerName, ICollection <Type> matchingTypes)
        {
            Contract.Requires(route != null);
            Contract.Requires(!string.IsNullOrEmpty(controllerName));
            Contract.Requires(matchingTypes != null);
            Contract.Ensures(Contract.Result <Exception>() != null);

            var builder = new StringBuilder();

            foreach (var type in matchingTypes)
            {
                builder.AppendLine();
                builder.Append(type.FullName);
            }

            var format = SR.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate;

            return(new InvalidOperationException(format.FormatDefault(controllerName, route.RouteTemplate, builder, NewLine)));
        }
        public void GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider(string httpMethod, string path, Type expectedProviderType)
        {
            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample" + path);

            request.Headers.Add("Origin", "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, httpMethod);
            HttpConfiguration config = new HttpConfiguration();

            request.SetConfiguration(config);
            IHttpRoute route = config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });

            request.SetRouteData(route.GetRouteData("/", request));

            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);

            Assert.True(request.GetCorsRequestContext().IsPreflight);
            Assert.IsType(expectedProviderType, provider);
        }
Пример #58
0
 public bool Match
 (
     HttpRequestMessage request,
     IHttpRoute route,
     string parameterName,
     IDictionary <string, object> values,
     HttpRouteDirection routeDirection
 )
 {
     if (routeDirection == HttpRouteDirection.UriResolution)
     {
         int version = GetVersionHeader(request) ?? DefaultVersion;
         if (version == AllowedVersion)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #59
0
        internal static string GetRouteName(this HttpRouteCollection routes, IHttpRoute route)
        {
            Contract.Requires(routes != null);
            Contract.Requires(route != null);

            var items = new KeyValuePair <string, IHttpRoute> [routes.Count];

            routes.CopyTo(items, 0);

            foreach (var item in items)
            {
                if (Equals(item.Value, route))
                {
                    return(item.Key);
                }
            }

            return(null);
        }
Пример #60
0
        public bool Match(
            HttpRequestMessage request,
            IHttpRoute route,
            string parameterName,
            IDictionary <string, object> values,
            HttpRouteDirection routeDirection)
        {
            object value;

            if (values.TryGetValue(parameterName, out value))
            {
                string pattern = "^(" + _regEx + ")$";
                string input   = Convert.ToString(value, CultureInfo.InvariantCulture);

                return(Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant));
            }

            return(false);
        }