public void AppliesToControllerWithRoutePrefixWorksAsExpected()
        {
            // Arrange
            ControllerModel controller = ControllerModelHelpers.BuildControllerModel <WithPrefixController>("List");
            ActionModel     action     = controller.Actions.First();

            ODataControllerActionContext context             = new ODataControllerActionContext(string.Empty, EdmModel, controller);
            AttributeRoutingConvention   attributeConvention = CreateConvention();

            // Act
            bool ok = attributeConvention.AppliesToController(context);

            Assert.False(ok);

            // Assert
            Assert.Equal(6, action.Selectors.Count);
            Assert.Equal(new[]
            {
                "Customers({key})",
                "Customers/{key}",
                "Customers",
                "Orders({key})",
                "Orders/{key}",
                "Orders",
            },
                         action.Selectors.Select(s => s.AttributeRouteModel.Template));
        }
Ejemplo n.º 2
0
        public CompositeKeyTest()
        {
            _configuration = new[]
            {
                typeof(MetadataController), typeof(DriverReleaseLifecycleDescriptionsController),
                typeof(AnyController)
            }.GetHttpConfiguration();

            IEdmModel model = CompositeEdmModel.GetEdmModel();

            // only convention routings
            var routingConventions = ODataRoutingConventions.CreateDefault();

            routingConventions.Insert(0, new CompositeKeyRoutingConvention());
            _configuration.MapODataServiceRoute("odata1", "odata", model, new DefaultODataPathHandler(), routingConventions);

            // only attribute routings
            var attrRouting = new AttributeRoutingConvention(model, _configuration);
            IList <IODataRoutingConvention> attributeRoutingConventions = new List <IODataRoutingConvention> {
                attrRouting
            };

            _configuration.MapODataServiceRoute("odata2", "attribute", model, new DefaultODataPathHandler(),
                                                attributeRoutingConventions);

            HttpServer server = new HttpServer(_configuration);

            _client = new HttpClient(server);
        }
Ejemplo n.º 3
0
        public void AppliesToControllerWithLongTemplateWorksAsExpected()
        {
            // Arrange
            ControllerModel controller = ControllerModelHelpers.BuildControllerModel <WithoutPrefixController>("LongAction");
            ActionModel     action     = controller.Actions.First();

            ODataControllerActionContext context             = new ODataControllerActionContext(string.Empty, EdmModel, controller);
            AttributeRoutingConvention   attributeConvention = CreateConvention();

            // Act
            bool ok = attributeConvention.AppliesToController(context);

            Assert.False(ok);

            // Assert
            Assert.Equal(4, action.Selectors.Count);
            Assert.Equal(new[]
            {
                "/Customers({key})/Orders({relatedKey})/NS.MyOrder/Title",
                "/Customers({key})/Orders/{relatedKey}/NS.MyOrder/Title",
                "/Customers/{key}/Orders({relatedKey})/NS.MyOrder/Title",
                "/Customers/{key}/Orders/{relatedKey}/NS.MyOrder/Title"
            },
                         action.Selectors.Select(s => s.AttributeRouteModel.Template));
        }
        public void AttributeMappingsIsInitialized_WithRightActionAndTemplate(Type controllerType,
                                                                              string expectedPathTemplate, string expectedActionName)
        {
            // Arrange
            var configuration   = RoutingConfigurationFactory.CreateWithRootContainer(RouteName);
            var serviceProvider = GetServiceProvider(configuration, RouteName);
            var request         = RequestFactory.Create(configuration, RouteName);
            var descriptors     = ControllerDescriptorFactory.Create(configuration, "TestController",
                                                                     controllerType);

            ODataPathTemplate pathTemplate = new ODataPathTemplate();
            Mock <IODataPathTemplateHandler> pathTemplateHandler = new Mock <IODataPathTemplateHandler>();

            pathTemplateHandler
            .Setup(p => p.ParseTemplate(expectedPathTemplate, serviceProvider))
            .Returns(pathTemplate)
            .Verifiable();

            AttributeRoutingConvention convention = new AttributeRoutingConvention(RouteName, descriptors, pathTemplateHandler.Object);

            // Act
            Select(convention, request);

            // Assert
            pathTemplateHandler.VerifyAll();
            Assert.NotNull(convention.AttributeMappings);
            Assert.Equal(expectedActionName, convention.AttributeMappings[pathTemplate].ActionName);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Apply Default OData attribute routing
        /// </summary>
        /// <param name="controllers">The controller models</param>
        internal void ApplyAttributeRouting(IList <ControllerModel> controllers)
        {
            AttributeRoutingConvention attributeRouting = _conventions.OfType <AttributeRoutingConvention>().FirstOrDefault();

            if (attributeRouting == null)
            {
                return;
            }

            ODataControllerActionContext controllerActionContext = new ODataControllerActionContext
            {
                Options = _options
            };

            foreach (var controllerModel in controllers.Where(c => !c.IsNonODataController()))
            {
                controllerActionContext.Controller = controllerModel;

                foreach (var actionModel in controllerModel.Actions.Where(a => !a.IsNonODataAction()))
                {
                    controllerActionContext.Action = actionModel;

                    attributeRouting.AppliesToAction(controllerActionContext);
                }
            }
        }
Ejemplo n.º 6
0
        public void CtorTakingHttpConfiguration_InitializesAttributeMappings_OnFirstSelectControllerCall()
        {
            // Arrange
            var config          = RoutingConfigurationFactory.CreateWithRootContainer(RouteName);
            var serviceProvider = GetServiceProvider(config, RouteName);
            var request         = RequestFactory.Create(config, RouteName);

#if NETCORE
            request.ODataFeature().Path = new ODataPath();
            request.Method = "Get";
            ControllerDescriptorFactory.Create(config, "MetadataAndService", typeof(MetadataAndServiceController));
#endif

            ODataPathTemplate pathTemplate = new ODataPathTemplate();
            Mock <IODataPathTemplateHandler> pathTemplateHandler = new Mock <IODataPathTemplateHandler>();
            pathTemplateHandler.Setup(p => p.ParseTemplate("$metadata", serviceProvider))
            .Returns(pathTemplate).Verifiable();

            AttributeRoutingConvention convention = CreateAttributeRoutingConvention(RouteName, config, pathTemplateHandler.Object);
            EnsureAttributeMapping(convention, config);

            // Act
            Select(convention, request);

            // Assert
            pathTemplateHandler.VerifyAll();
            Assert.NotNull(convention.AttributeMappings);
            Assert.Equal("GetMetadata", convention.AttributeMappings[pathTemplate].ActionName);
        }
 static AttributeRoutingConventionTests()
 {
     _edmModel = GetEdmModel();
     _options  = new ODataOptions();
     _options.AddModel(_edmModel);
     _attributeConvention = CreateConvention();
 }
Ejemplo n.º 8
0
        public void AttributeMappingsInitialization_ThrowsInvalidOperation_IfNoConfigEnsureInitialized()
        {
            // Arrange
            var configuration = RoutingConfigurationFactory.CreateWithRootContainer(RouteName);
            AttributeRoutingConvention convention = CreateAttributeRoutingConvention(RouteName, configuration);

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(
                () => convention.AttributeMappings,
                "The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called " +
                "in the application's startup code after all other initialization code.");
        }
Ejemplo n.º 9
0
        public void AttributeRoutingConvention_ConfigEnsureInitialized_DoesNotThrowForValidPathTemplate()
        {
            // Arrange
            IEdmModel model         = new CustomersModelWithInheritance().Model;
            var       configuration = RoutingConfigurationFactory.CreateWithRootContainerAndTypes(
                RouteName,
                (b => b.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => model)),
                typeof(TestODataController));

            AttributeRoutingConvention convention = CreateAttributeRoutingConvention(RouteName, configuration);

            // Act & Assert
            ExceptionAssert.DoesNotThrow(() => EnsureAttributeMapping(convention, configuration));
        }
Ejemplo n.º 10
0
        public void AttributeRoutingConvention_ConfigEnsureInitialized_ThrowsForInvalidPathTemplate()
        {
            // Arrange
            var configuration = RoutingConfigurationFactory.CreateWithRootContainerAndTypes(RouteName, null, typeof(TestODataController));

#if NETCORE
            ControllerDescriptorFactory.Create(configuration, "TestOData", typeof(TestODataController));
#endif

            AttributeRoutingConvention convention = CreateAttributeRoutingConvention(RouteName, configuration);

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(
                () => EnsureAttributeMapping(convention, configuration),
                "The path template 'Customers' on the action 'GetCustomers' in controller 'TestOData' is not a valid OData path template. " +
                "Resource not found for the segment 'Customers'.");
        }
        public void AttributeRoutingConvention_ConfigEnsureInitialized_ThrowsForInvalidPathTemplate()
        {
            // Arrange
            var configuration = RoutingConfigurationFactory.CreateWithRootContainerAndTypes(RouteName, null, typeof(TestODataController));

#if NETCORE
            ControllerDescriptorFactory.Create(configuration, "TestOData", typeof(TestODataController));
#endif

            AttributeRoutingConvention convention = CreateAttributeRoutingConvention(RouteName, configuration);

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(
                () => EnsureAttributeMapping(convention, configuration),
                "The path template 'Customers' on the action 'GetCustomers' in controller 'TestOData' is not a valid OData path template. " +
                "The operation import overloads matching 'Customers' are invalid. This is most likely an error in the IEdmModel.");
        }
        public void AppliesToActionWithRoutePrefixWorksAsExpected()
        {
            // Arrange
            ControllerModel controller = ControllerModelHelpers.BuildControllerModel <WithPrefixController>("List");
            ActionModel     action     = controller.Actions.First();

            Assert.Equal(2, action.Selectors.Count);

            ODataControllerActionContext context = new ODataControllerActionContext(string.Empty, _edmModel, controller)
            {
                Action  = action,
                Options = _options,
            };

            AttributeRoutingConvention attributeConvention = CreateConvention();

            // Act
            bool ok = _attributeConvention.AppliesToAction(context);

            Assert.False(ok);

            // Assert
            Assert.Equal(4, action.Selectors.Count);
            Assert.Collection(action.Selectors,
                              e =>
            {
                Assert.Equal("/Customers/{key}", e.AttributeRouteModel.Template);
                Assert.Contains(e.EndpointMetadata, a => a is ODataRoutingMetadata);
            },
                              e =>
            {
                Assert.Equal("/Orders/{key}", e.AttributeRouteModel.Template);
                Assert.Contains(e.EndpointMetadata, a => a is ODataRoutingMetadata);
            },
                              e =>
            {
                Assert.Equal("/Customers", e.AttributeRouteModel.Template);
                Assert.Contains(e.EndpointMetadata, a => a is ODataRoutingMetadata);
            },
                              e =>
            {
                Assert.Equal("/Orders", e.AttributeRouteModel.Template);
                Assert.Contains(e.EndpointMetadata, a => a is ODataRoutingMetadata);
            });
        }
Ejemplo n.º 13
0
        public void AppliesToControllerForSingletonWorksAsExpected(string actionName, string expectedTemplate)
        {
            // Arrange
            ControllerModel controller = ControllerModelHelpers.BuildControllerModel <SingletonTestControllerWithPrefix>(actionName);
            ActionModel     action     = controller.Actions.First();

            ODataControllerActionContext context             = new ODataControllerActionContext(string.Empty, EdmModel, controller);
            AttributeRoutingConvention   attributeConvention = CreateConvention();

            // Act
            bool ok = attributeConvention.AppliesToController(context);

            Assert.False(ok);

            // Assert
            SelectorModel selector = Assert.Single(action.Selectors);

            Assert.NotNull(selector.AttributeRouteModel);
            Assert.Equal(expectedTemplate, selector.AttributeRouteModel.Template);
        }
Ejemplo n.º 14
0
 private string Select(AttributeRoutingConvention convention, HttpRequestMessage request)
 {
     return(convention.SelectController(new ODataPath(), request));
 }
Ejemplo n.º 15
0
 private void EnsureAttributeMapping(AttributeRoutingConvention convention, HttpConfiguration configuration)
 {
     configuration.EnsureInitialized();
 }
Ejemplo n.º 16
0
        private ControllerActionDescriptor Select(AttributeRoutingConvention convention, HttpRequest request)
        {
            RouteContext routeContext = new RouteContext(request.HttpContext);

            return(convention.SelectAction(routeContext)?.FirstOrDefault());
        }
Ejemplo n.º 17
0
 private void EnsureAttributeMapping(AttributeRoutingConvention convention, IRouteBuilder routeBuilder)
 {
     var mappings = convention.AttributeMappings;
 }
        private static IDictionary <ODataPathTemplate, HttpActionDescriptor> BuildAttributeMappings(ICollection <HttpControllerDescriptor> controllers,
                                                                                                    AttributeRoutingConvention routingConvention)
        {
            IDictionary <ODataPathTemplate, HttpActionDescriptor> attributeMappings =
                new Dictionary <ODataPathTemplate, HttpActionDescriptor>();

            foreach (HttpControllerDescriptor controller in controllers)
            {
                if (IsODataController(controller) && ShouldMapController(controller))
                {
                    IHttpActionSelector actionSelector = controller.Configuration.Services.GetActionSelector();
                    ILookup <string, HttpActionDescriptor> actionMapping = actionSelector.GetActionMapping(controller);
                    HttpActionDescriptor[] actions = actionMapping.SelectMany(a => a).ToArray();

                    foreach (string prefix in GetODataRoutePrefixes(controller))
                    {
                        foreach (HttpActionDescriptor action in actions)
                        {
                            IEnumerable <ODataPathTemplate> pathTemplates = // Invoke private method
                                                                            routingConvention.InvokeFunction <IEnumerable <ODataPathTemplate> >("GetODataPathTemplates", prefix, action);
                            foreach (ODataPathTemplate pathTemplate in pathTemplates)
                            {
                                //attributeMappings.Add(pathTemplate, new WebApiActionDescriptor(action));
                                attributeMappings.Add(pathTemplate, action);
                            }
                        }
                    }
                }
            }

            return(attributeMappings);
        }
        private static IDictionary <ODataPathTemplate, HttpActionDescriptor> GetAttributeRoutingActionMap(HttpConfiguration httpConfig,
                                                                                                          AttributeRoutingConvention routingConvention)
        {
            IHttpControllerSelector controllerSelector = httpConfig.Services.GetHttpControllerSelector();

            return(BuildAttributeMappings(controllerSelector.GetControllerMapping().Values, routingConvention));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Maps the OData route attributes.
        /// </summary>
        /// <param name="configuration">The http configuration used to search for all the OData controllers to map.</param>
        public void MapODataRouteAttributes(HttpConfiguration configuration)
        {
            AttributeRoutingConvention routingConvention = new AttributeRoutingConvention(PathRouteConstraint.EdmModel, configuration);

            PathRouteConstraint.RoutingConventions.Insert(0, routingConvention);
        }