Пример #1
0
        public async Task BadReturnTypeThrows(string methodName)
        {
            // Arrange
            ODataQueryParameterBindingAttribute attribute = new ODataQueryParameterBindingAttribute();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?$orderby=Name");
            var config = RoutingConfigurationFactory.Create();

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            request.SetConfiguration(config);
            HttpControllerContext    controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerLowLevel", typeof(CustomerHighLevelController));
            MethodInfo              methodInfo            = typeof(CustomerLowLevelController).GetMethod(methodName);
            ParameterInfo           parameterInfo         = methodInfo.GetParameters().First();
            HttpActionDescriptor    actionDescriptor      = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo);
            HttpActionContext       actionContext         = new HttpActionContext(controllerContext, actionDescriptor);
            HttpParameterDescriptor parameterDescriptor   = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);

            // Act
            HttpParameterBinding binding = attribute.GetBinding(parameterDescriptor);

            // Act & Assert
            await ExceptionAssert.ThrowsAsync <InvalidOperationException>(
                () => binding.ExecuteBindingAsync((ModelMetadataProvider)null, actionContext, CancellationToken.None),
                String.Format(
                    "Cannot create an EDM model as the action '{0}' on controller '{1}' has a return type '{2}' that does not implement IEnumerable<T>.",
                    actionDescriptor.ActionName,
                    actionDescriptor.ControllerDescriptor.ControllerName,
                    actionDescriptor.ReturnType.FullName));
        }
Пример #2
0
        public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
        {
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet = model.EntityContainer.FindEntitySet("vehicles");
            IEdmEntityType         carType = model.AssertHasEntityType(typeof(Car));
            IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName);

            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);

            linkBuilder.AddNavigationPropertyLinkBuilder(carManufacturerProperty, new NavigationLinkBuilder((context, property) => context.GenerateNavigationPropertyLink(property, includeCast: true), false));
            var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request);
            var entityContext     = new ResourceContext(serializerContext, carType.AsReference(), new Car {
                Model = 2009, Name = "Accord"
            });

            Uri uri = linkBuilder.BuildNavigationLink(entityContext, carManufacturerProperty, ODataMetadataLevel.MinimalMetadata);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/Microsoft.AspNet.OData.Test.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
        }
Пример #3
0
        public void ODataVersionConstraint_DefaultValue()
        {
            var        config     = RoutingConfigurationFactory.Create();
            ODataRoute odataRoute = CreateRoute(config, routePrefix: null);

            Assert.True(((ODataVersionConstraint)odataRoute.Constraints[ODataRouteConstants.VersionConstraintName]).IsRelaxedMatch);
        }
        public void Convention_GeneratesUri_ForActionBoundToEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Customer>("Customers");
            var action = builder.EntityType <Customer>().Action("MyAction");

            action.Parameter <string>("param");
            IEdmModel model = builder.GetEdmModel();

            // Act
            var configuration = RoutingConfigurationFactory.Create();

            configuration.MapODataServiceRoute("odata", "odata", model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost:123", configuration, "odata");

            IEdmEntitySet customers         = model.EntityContainer.FindEntitySet("Customers");
            var           edmType           = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "Customer");
            var           serializerContext = ODataSerializerContextFactory.Create(model, customers, request);
            var           resourceContext   = new ResourceContext(serializerContext, edmType.AsReference(), new Customer {
                Id = 109
            });

            // Assert
            var edmAction = model.SchemaElements.OfType <IEdmAction>().First(f => f.Name == "MyAction");

            Assert.NotNull(edmAction);

            OperationLinkBuilder actionLinkBuilder = model.GetOperationLinkBuilder(edmAction);
            Uri link = actionLinkBuilder.BuildLink(resourceContext);

            Assert.Equal("http://localhost:123/odata/Customers(109)/Default.MyAction", link.AbsoluteUri);
        }
        public void Convention_GeneratesUri_ForActionBoundToCollectionOfEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Customer>("Customers");
            var action = builder.EntityType <Customer>().Collection.Action("MyAction").Returns <int>();

            action.Parameter <string>("param");
            IEdmModel model = builder.GetEdmModel();

            // Act
            var configuration = RoutingConfigurationFactory.Create();

            configuration.MapODataServiceRoute("odata", "odata", model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost:123", configuration, "odata");

            IEdmEntitySet customers     = model.EntityContainer.FindEntitySet("Customers");
            var           entityContext = ResourceSetContextFactory.Create(customers, request);

            // Assert
            var edmAction = model.SchemaElements.OfType <IEdmAction>().First(f => f.Name == "MyAction");

            Assert.NotNull(edmAction);

            OperationLinkBuilder actionLinkBuilder = model.GetOperationLinkBuilder(edmAction);
            Uri link = actionLinkBuilder.BuildLink(entityContext);

            Assert.Equal("http://localhost:123/odata/Customers/Default.MyAction", link.AbsoluteUri);
        }
        public void WhenActionLinksNotManuallyConfigured_ConventionBasedBuilderUsesConventions()
        {
            // Arrange
            string            uriTemplate         = "http://server/Movies({0})/Default.Watch";
            Uri               expectedUri         = new Uri(string.Format(uriTemplate, 1));
            ODataModelBuilder builder             = ODataConventionModelBuilderFactory.Create();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            ActionConfiguration             watch = movie.Action("Watch");
            IEdmModel model = builder.GetEdmModel();

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://server/Movies", configuration, routeName);

            // Act
            IEdmEntityType         movieType         = model.SchemaElements.OfType <IEdmEntityType>().SingleOrDefault();
            IEdmEntityContainer    container         = model.SchemaElements.OfType <IEdmEntityContainer>().SingleOrDefault();
            IEdmAction             watchAction       = Assert.Single(model.SchemaElements.OfType <IEdmAction>()); // Guard
            IEdmEntitySet          entitySet         = container.EntitySets().SingleOrDefault();
            ODataSerializerContext serializerContext = ODataSerializerContextFactory.Create(model, entitySet, request);

            ResourceContext context = new ResourceContext(serializerContext, movieType.AsReference(), new Movie {
                ID = 1, Name = "Avatar"
            });
            OperationLinkBuilder actionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(watchAction);

            //Assert
            Assert.Equal(expectedUri, watch.GetActionLink()(context));
            Assert.NotNull(actionLinkBuilder);
            Assert.Equal(expectedUri, actionLinkBuilder.BuildLink(context));
        }
Пример #7
0
        public void WhenFeedActionLinksNotManuallyConfigured_ConventionBasedBuilderUsesConventions()
        {
            // Arrange
            Uri expectedUri                       = new Uri("http://server/Movies/Default.Watch(param=@param)");
            ODataModelBuilder builder             = ODataConventionModelBuilderFactory.Create();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            FunctionConfiguration           watch = movie.Collection.Function("Watch").Returns <int>(); // function bound to collection

            watch.Parameter <string>("param");
            IEdmModel model = builder.GetEdmModel();

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://server/Movies", configuration, routeName);

            // Act
            IEdmEntityContainer container     = model.SchemaElements.OfType <IEdmEntityContainer>().SingleOrDefault();
            IEdmFunction        watchFunction = Assert.Single(model.SchemaElements.OfType <IEdmFunction>()); // Guard
            IEdmEntitySet       entitySet     = container.EntitySets().SingleOrDefault();

            ODataSerializerContextFactory.Create(model, entitySet, request);
            ResourceSetContext context = ResourceSetContextFactory.Create(entitySet, request);

            OperationLinkBuilder functionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(watchFunction);

            //Assert
            Assert.Equal(expectedUri, watch.GetFeedFunctionLink()(context));
            Assert.NotNull(functionLinkBuilder);
            Assert.Equal(expectedUri, functionLinkBuilder.BuildLink(context));
        }
Пример #8
0
        public async Task SendAsync_ReturnsNotFoundForNullEntityResponse()
        {
            // Arrange
            Mock <MediaTypeFormatter> formatter = new Mock <MediaTypeFormatter>();

            formatter.Setup(f => f.CanWriteType(It.IsAny <Type>())).Returns(true);

            HttpResponseMessage originalResponse = new HttpResponseMessage(HttpStatusCode.OK);

            originalResponse.Content = new ObjectContent(typeof(string), null, formatter.Object);

            ODataNullValueMessageHandler handler = new ODataNullValueMessageHandler
            {
                InnerHandler = new TestMessageHandler(originalResponse)
            };

            var                configuration = RoutingConfigurationFactory.Create();
            ODataPath          path          = new DefaultODataPathHandler().Parse(BuildModel(), "http://localhost/any", "Customers(3)");
            HttpRequestMessage request       = RequestFactory.Create(HttpMethod.Get, "http://localhost/any", configuration);

            request.ODataContext().Path = path;

            // Act
            HttpResponseMessage response = await handler.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
Пример #9
0
        public void CtorTakingModelAndConfiguration_ThrowsArgumentNull_RouteName()
        {
            var configuration = RoutingConfigurationFactory.Create();

            ExceptionAssert.ThrowsArgumentNull(
                () => CreateAttributeRoutingConvention(null, configuration),
                "routeName");
        }
Пример #10
0
        public void CanGenerateDirectLink_IsFalse_IfRouteTemplateHasParameterInPrefix()
        {
            // Arrange && Act
            var        config     = RoutingConfigurationFactory.Create();
            ODataRoute odataRoute = CreateRoute(config, "{prefix}");

            // Assert
            Assert.False(odataRoute.CanGenerateDirectLink);
        }
Пример #11
0
        public void GetFilters_ReturnsEmptyCollection_ForNonQueryableActions(string actionName)
        {
            var config = RoutingConfigurationFactory.Create();
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "FilterProviderTest", typeof(FilterProviderTestController));
            HttpActionDescriptor     actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(FilterProviderTestController).GetMethod(actionName));

            FilterInfo[] filters = new QueryFilterProvider(new EnableQueryAttribute()).GetFilters(config, actionDescriptor).ToArray();

            Assert.Empty(filters);
        }
        private HttpRequestMessage GetRequest(IEdmModel model, IEdmSingleton singleton)
#endif
        {
            var config = RoutingConfigurationFactory.Create();

            config.MapODataServiceRoute("odata", "odata", model);
            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost/odata/Boss", config, "odata");

            request.ODataContext().Path = new ODataPath(new[] { new SingletonSegment(singleton) });
            return(request);
        }
Пример #13
0
        public void GetFilters_ReturnsQueryableFilter_ForQueryableActions(string actionName)
        {
            var config = RoutingConfigurationFactory.Create();
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "FilterProviderTest", typeof(FilterProviderTestController));
            HttpActionDescriptor     actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(FilterProviderTestController).GetMethod(actionName));

            FilterInfo[] filters = new QueryFilterProvider(new EnableQueryAttribute()).GetFilters(config, actionDescriptor).ToArray();

            Assert.Single(filters);
            Assert.Equal(FilterScope.Global, filters[0].Scope);
            EnableQueryAttribute filter = Assert.IsType <EnableQueryAttribute>(filters[0].Instance);
        }
Пример #14
0
        public void GetBinding_DoesnotThrowForNonPrimitives()
        {
            var  config        = RoutingConfigurationFactory.Create();
            Type parameterType = typeof(FormatterOrder);
            Mock <ParameterInfo> parameterInfoMock = new Mock <ParameterInfo>();

            parameterInfoMock.Setup(info => info.ParameterType).Returns(parameterType);
            ReflectedHttpParameterDescriptor parameter = new ReflectedHttpParameterDescriptor();

            parameter.Configuration = config;
            parameter.ParameterInfo = parameterInfoMock.Object;

            ExceptionAssert.DoesNotThrow(() => new FromODataUriAttribute().GetBinding(parameter));
        }
Пример #15
0
        public void SelectExpandClause_CanParse_ModelBuiltForQueryable(string select, string expand)
        {
            // Arrange
            var config = RoutingConfigurationFactory.Create();
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(config, isQueryCompositionMode: true);
            builder.EntityType<Customer>();
            IEdmModel model = builder.GetEdmModel();

            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));
            context.RequestContainer = new MockContainer();
            SelectExpandQueryOption option = new SelectExpandQueryOption(select, expand, context);

            // Act & Assert
            ExceptionAssert.DoesNotThrow(() => option.SelectExpandClause.ToString());
        }
Пример #16
0
        public async Task ComplexTypeSerializesAsOData()
        {
            // Arrange
            string    routeName = "OData";
            IEdmModel model     = GetSampleModel();
            var       config    = RoutingConfigurationFactory.Create();

            config = RoutingConfigurationFactory.CreateWithRootContainer(routeName, b => b.AddService(ServiceLifetime.Singleton, s => model));
            var request   = RequestFactory.Create(HttpMethod.Get, "http://localhost/property", config, routeName);
            var payload   = new ODataPayloadKind[] { ODataPayloadKind.Resource };
            var formatter = FormatterTestHelper.GetFormatter(payload, request);
            var content   = FormatterTestHelper.GetContent(new Person(0, new ReferenceDepthContext(7)), formatter,
                                                           ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.PersonComplexType, await FormatterTestHelper.GetContentResult(content, request));
        }
Пример #17
0
        public void GenerateLinkDirectly_DoesNotReturnNull_IfHelperRequestHasNoConfiguration()
        {
            // Arrange
            var        config     = RoutingConfigurationFactory.Create();
            ODataRoute odataRoute = CreateRoute(config, "prefix");

            // Act
            var virtualPathData = odataRoute.GenerateLinkDirectly("odataPath");

            // Assert
            Assert.True(odataRoute.CanGenerateDirectLink);
            Assert.NotNull(virtualPathData);
#if NETCORE
            Assert.Equal("/prefix/odataPath", virtualPathData.VirtualPath);
#else
            Assert.Equal("prefix/odataPath", virtualPathData.VirtualPath);
#endif
        }
Пример #18
0
        public void ApplyProperty_FailWithTwoCaseInsensitiveMatchesAndCaseSensitiveMatch()
        {
            const string expectedErrorMessage = "The property 'proPerty1' does not exist on type 'namespace.name'. Make sure to only use property names that are defined by the type.";
            // Arrange
            ODataProperty property = new ODataProperty {
                Name = "proPerty1", Value = "Value1"
            };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");

            entityType.AddStructuralProperty("Property1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)));
            entityType.AddStructuralProperty("property1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)));
            entityType.AddKeys(entityType.AddStructuralProperty("Key1",
                                                                EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));

            EdmEntityTypeReference    entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider            = ODataDeserializerProviderFactory.Create();

#if NETCORE
            IRouteBuilder builder = RoutingConfigurationFactory.Create();

            HttpRequest request = RequestFactory.Create(builder);
#else
            HttpConfiguration  configuration = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            HttpRequestMessage request       = RequestFactory.Create(configuration);
#endif

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Model   = new EdmModel(),
                Request = request
            };

            // Act
            var exception = Assert.Throws <ODataException>(() =>
                                                           DeserializationHelpers.ApplyProperty(
                                                               property,
                                                               entityTypeReference,
                                                               resource: null,
                                                               provider,
                                                               context));

            // Assert
            Assert.Equal(expectedErrorMessage, exception.Message);
        }
Пример #19
0
        public void GetBinding_ReturnsSameBindingTypeAsODataModelBinderProvider()
        {
            var  config        = RoutingConfigurationFactory.Create();
            Type parameterType = typeof(Guid);
            Mock <ParameterInfo> parameterInfoMock = new Mock <ParameterInfo>();

            parameterInfoMock.Setup(info => info.ParameterType).Returns(parameterType);

            ReflectedHttpParameterDescriptor parameter = new ReflectedHttpParameterDescriptor();

            parameter.Configuration = config;
            parameter.ParameterInfo = parameterInfoMock.Object;

            HttpParameterBinding binding = new FromODataUriAttribute().GetBinding(parameter);

            ModelBinderParameterBinding modelBinding = Assert.IsType <ModelBinderParameterBinding>(binding);

            Assert.Equal(new ODataModelBinderProvider().GetBinder(config, parameterType).GetType(), modelBinding.Binder.GetType());
        }
Пример #20
0
        public void ApplyProperty_PassesWithCaseInsensitivePropertyName()
        {
            // Arrange
            ODataProperty property = new ODataProperty {
                Name = "keY1", Value = "Value1"
            };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");

            entityType.AddKeys(entityType.AddStructuralProperty("Key1",
                                                                EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));

            EdmEntityTypeReference    entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider            = ODataDeserializerProviderFactory.Create();

            var  resource     = new Mock <IDelta>(MockBehavior.Strict);
            Type propertyType = typeof(string);

            resource.Setup(r => r.TryGetPropertyType("Key1", out propertyType)).Returns(true).Verifiable();
            resource.Setup(r => r.TrySetPropertyValue("Key1", "Value1")).Returns(true).Verifiable();

#if NETCORE
            IRouteBuilder builder = RoutingConfigurationFactory.Create();

            HttpRequest request = RequestFactory.Create(builder);
#else
            HttpConfiguration  configuration = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            HttpRequestMessage request       = RequestFactory.Create(configuration);
#endif

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Model   = new EdmModel(),
                Request = request
            };

            // Act
            DeserializationHelpers.ApplyProperty(property, entityTypeReference, resource.Object, provider,
                                                 context);

            // Assert
            resource.Verify();
        }
Пример #21
0
        public void NavigationLinksGenerationConvention_GeneratesLinksWithoutCast_ForBaseProperties()
        {
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <SportBike>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet           = model.EntityContainer.FindEntitySet("vehicles");
            IEdmEntityType         sportbikeType                  = model.AssertHasEntityType(typeof(SportBike));
            IEdmNavigationProperty motorcycleManufacturerProperty = sportbikeType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName);

            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);

            linkBuilder.AddNavigationPropertyLinkBuilder(motorcycleManufacturerProperty, new NavigationLinkBuilder((context, property) => context.GenerateNavigationPropertyLink(property, includeCast: false), false));
            var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request);
            var entityContext     = new ResourceContext(serializerContext, sportbikeType.AsReference(), new SportBike {
                Model = 2009, Name = "Ninja"
            });

            // We might get one of these:
            // http://localhost/vehicles(Model=2009,Name='Ninja')/Manufacturer
            // http://localhost/vehicles(Name='Ninja',Model=2009)/Manufacturer
            Uri    uri        = linkBuilder.BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.MinimalMetadata);
            string aboluteUri = uri.AbsoluteUri;

            Assert.Contains("http://localhost/vehicles(", aboluteUri);
            Assert.Contains("Model=2009", aboluteUri);
            Assert.Contains("Name='Ninja'", aboluteUri);
            Assert.Contains(")/Manufacturer", aboluteUri);
        }
Пример #22
0
        /// <summary>
        /// Test method to call constraint.Match using the proper arguments for each platform.
        /// </summary>
        /// <param name="constraint">The constraint object.</param>
        /// <param name="routeRequest">The abstracted request.</param>
        /// <param name="direction">The abstracted route direction.</param>
        /// <returns>Result from constraint.Match,</returns>
        private bool ConstraintMatch(ODataPathRouteConstraint constraint, TestRouteRequest routeRequest, Dictionary <string, object> values, RouteDirection direction)
        {
#if NETCORE
            IRouteBuilder config = RoutingConfigurationFactory.Create();
            if (routeRequest?.PathHandler != null && routeRequest?.Model != null)
            {
                config.MapODataServiceRoute(_routeName, "", builder =>
                                            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.PathHandler)
                                            .AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.Model));
            }
            else if (routeRequest?.PathHandler != null)
            {
                config.MapODataServiceRoute(_routeName, "", builder =>
                                            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.PathHandler));
            }
            else if (routeRequest?.Model != null)
            {
                config.MapODataServiceRoute(_routeName, "", builder =>
                                            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.Model));
            }
            else
            {
                config.MapODataServiceRoute(_routeName, "", builder => { });
            }

            HttpRequest request = (routeRequest != null)
                ? RequestFactory.Create(routeRequest.Method, routeRequest.Uri, config, _routeName)
                : RequestFactory.Create();

            // The RequestFactory will create a request container which most tests want but for checking the constraint,
            // we don't want a request container before the test runs since Match() creates one.
            request.DeleteRequestContainer(true);

            if (routeRequest != null)
            {
                routeRequest.InnerRequest = request;
            }

            AspNetCore.Routing.RouteDirection routeDirection = (direction == RouteDirection.UriResolution)
                ? AspNetCore.Routing.RouteDirection.IncomingRequest
                : AspNetCore.Routing.RouteDirection.UrlGeneration;

            RouteValueDictionary routeValues = new RouteValueDictionary(values);

            return(constraint.Match(request.HttpContext, null, null, routeValues, routeDirection));
#else
            HttpRequestMessage request = (routeRequest != null)
                ? new HttpRequestMessage(routeRequest.Method, routeRequest.Uri)
                : new HttpRequestMessage();

            var httpRouteCollection = new HttpRouteCollection
            {
                { _routeName, new HttpRoute() },
            };

            var configuration = new HttpConfiguration(httpRouteCollection);
            if (routeRequest != null && routeRequest.PathHandler != null && routeRequest.Model != null)
            {
                configuration.CreateODataRootContainer(_routeName, builder =>
                                                       builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.PathHandler)
                                                       .AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.Model));
            }
            else if (routeRequest != null && routeRequest.PathHandler != null)
            {
                configuration.CreateODataRootContainer(_routeName, builder =>
                                                       builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.PathHandler));
            }
            else if (routeRequest != null && routeRequest.Model != null)
            {
                configuration.CreateODataRootContainer(_routeName, builder =>
                                                       builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => routeRequest.Model));
            }
            else
            {
                PerRouteContainer perRouteContainer = configuration.GetPerRouteContainer() as PerRouteContainer;
                perRouteContainer.SetODataRootContainer(_routeName, _rootContainer);
            }

            request.SetConfiguration(configuration);
            if (routeRequest != null)
            {
                routeRequest.InnerRequest = request;
            }

            HttpRouteDirection routeDirection = (direction == RouteDirection.UriResolution)
                ? HttpRouteDirection.UriResolution
                : HttpRouteDirection.UriGeneration;

            return(constraint.Match(request, null, null, values, routeDirection));
#endif
        }