Beispiel #1
0
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes"></param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes.
        /// </param>
        public static void MapMvcAttributeRoutes(
            this RouteCollection routes,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

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

            AttributeRoutingMapper.MapAttributeRoutes(
                routes,
                constraintResolver,
                directRouteProvider
                );
        }
        public void CreateRoute_IfBuilderContraintsIsNotNullAndConstraintsPropertyIsNull_UsesBuilderConstraints()
        {
            // Arrange
            HttpRouteValueDictionary existingConstraints = new HttpRouteValueDictionary();

            Mock <RouteProviderAttribute> productMock = CreateProductUnderTestMock();

            productMock.SetupGet(p => p.Constraints).Returns((HttpRouteValueDictionary)null);
            IDirectRouteProvider product = productMock.Object;

            HttpRouteEntry expectedEntry = CreateEntry();

            HttpRouteValueDictionary constraints = null;
            DirectRouteBuilder       builder     = null;

            builder = CreateBuilder(() =>
            {
                constraints = builder.Constraints;
                return(null);
            });

            builder.Constraints = existingConstraints;

            DirectRouteProviderContext context = CreateContext((i) => builder);

            // Act
            HttpRouteEntry ignore = product.CreateRoute(context);

            // Assert
            Assert.Same(existingConstraints, constraints);
        }
        public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Assembly assembly, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
        {
            var controllers = (assembly.GetExportedTypes()
                .Where(IsControllerType)).ToList();

            MapAttributeRoutesInControllers(routes, controllers, constraintResolver, routeProvider);
        }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(
            RouteCollection routes, 
            IInlineConstraintResolver constraintResolver, 
            IDirectRouteProvider directRouteProvider)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

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

            DefaultControllerFactory typesLocator =
                DependencyResolver.Current.GetService<IControllerFactory>() as DefaultControllerFactory
                ?? ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory
                ?? new DefaultControllerFactory();

            IReadOnlyList<Type> controllerTypes = typesLocator.GetControllerTypes();

            MapAttributeRoutes(routes, controllerTypes, constraintResolver, directRouteProvider);
        }
Beispiel #5
0
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for discovering and building routes.
        /// </param>
        // Corresponds to the MVC implementation of attribute routing in
        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.
        public static void MapHttpAttributeRoutes(
            this HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

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

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

            AttributeRoutingMapper.MapAttributeRoutes(
                configuration,
                constraintResolver,
                directRouteProvider
                );
        }
Beispiel #6
0
        private static async Task <HttpResponseMessage> SubmitRequestAsync(
            HttpRequestMessage request,
            IDirectRouteProvider routeProvider = null
            )
        {
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}");
            if (routeProvider == null)
            {
                config.MapHttpAttributeRoutes();
            }
            else
            {
                config.MapHttpAttributeRoutes(routeProvider);
            }

            HttpResponseMessage response;
            HttpServer          server = new HttpServer(config);

            using (HttpMessageInvoker client = new HttpMessageInvoker(server))
            {
                response = await client.SendAsync(request, CancellationToken.None);
            }

            return(response);
        }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(
            RouteCollection routes,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

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

            DefaultControllerFactory typesLocator =
                DependencyResolver.Current.GetService <IControllerFactory>()
                as DefaultControllerFactory
                ?? ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory
                ?? new DefaultControllerFactory();

            IReadOnlyList <Type> controllerTypes = typesLocator.GetControllerTypes();

            MapAttributeRoutes(routes, controllerTypes, constraintResolver, directRouteProvider);
        }
        public static void MapAttributeRoutes(
            HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

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

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

            RouteCollectionRoute aggregateRoute = new RouteCollectionRoute();

            configuration.Routes.Add(AttributeRouteName, aggregateRoute);

            Action <HttpConfiguration> previousInitializer = configuration.Initializer;

            configuration.Initializer = config =>
            {
                // Chain to the previous initializer hook. Do this before we access the config since
                // initialization may make last minute changes to the configuration.
                previousInitializer(config);

                SubRouteCollection subRoutes = null;

                // Add a single placeholder route that handles all of attribute routing.
                // Add an initialize hook that initializes these routes after the config has been initialized.
                Func <SubRouteCollection> initializer = () =>
                {
                    subRoutes = new SubRouteCollection();
                    AddRouteEntries(
                        subRoutes,
                        configuration,
                        constraintResolver,
                        directRouteProvider
                        );
                    return(subRoutes);
                };

                // This won't change config. It wants to pick up the finalized config.
                aggregateRoute.EnsureInitialized(initializer);

                if (subRoutes != null)
                {
                    AddGenerationHooksForSubRoutes(config.Routes, subRoutes.Entries);
                }
            };
        }
 public DecoratorRouteProvider(IDirectRouteProvider provider)
 {
     _provider = provider;
     RouteMap = methodInfo =>
     {
         RouteEntry entry;
         return _map.TryGetValue(methodInfo, out entry) ? entry : null;
     };
 }
Beispiel #10
0
 public DecoratorRouteProvider(IDirectRouteProvider provider, Func <HttpRequestMessage, ICollection <RouteEntry>, RouteEntry> routeSelector = null)
 {
     _provider      = provider;
     _routeSelector = routeSelector;
     RouteMap       = methodInfo =>
     {
         MethodHandler entry;
         return(_map.TryGetValue(methodInfo, out entry) ? entry : null);
     };
 }
 public static UriMakerContext MapHttpAttributeRoutesAndUseUriMaker(
     this HttpConfiguration configuration,
     IDirectRouteProvider directRouteProvider = null)
 {
     directRouteProvider = directRouteProvider ?? new DefaultDirectRouteProvider();
     var decorator = new DecoratorRouteProvider(directRouteProvider);
     configuration.MapHttpAttributeRoutes(decorator);
     var uriMakerContext = new UriMakerContext(decorator.RouteMap);
     return uriMakerContext;
 }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="controllerTypes">The controller types to scan.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(
            RouteCollection routes,
            IEnumerable <Type> controllerTypes,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

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

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

            SubRouteCollection subRoutes = new SubRouteCollection();

            AddRouteEntries(subRoutes, controllerTypes, constraintResolver, directRouteProvider);
            IReadOnlyCollection <RouteEntry> entries = subRoutes.Entries;

            if (entries.Count > 0)
            {
                RouteCollectionRoute aggregrateRoute = new RouteCollectionRoute(subRoutes);
                routes.Add(aggregrateRoute);

                // This sort is here to enforce a static ordering for link generation using these routes.
                // We don't apply dynamic criteria like ActionSelectors on link generation, but we can use the static
                // ones.
                //
                // Routes to actions are placed first because they are considered more specific. A route to an action
                // will only match for link generation if the action name was supplied, so this is essential for
                // correctness. Without this a controller-level route could be 'greedy' and generate a link when
                // the action-level route was intended.
                RouteEntry[] sorted = entries
                                      .OrderBy(r => r.Route.GetOrder())
                                      .ThenBy(r => r.Route.GetTargetIsAction() ? 0 : 1)
                                      .ThenBy(r => r.Route.GetPrecedence())
                                      .ToArray();

                AddGenerationHooksForSubRoutes(routes, sorted);
            }
        }
 public static UriMakerContext MapHttpAttributeRoutesAndUseUriMaker(
     this HttpConfiguration configuration,
     IDirectRouteProvider directRouteProvider = null,
     Func<HttpRequestMessage, ICollection<RouteEntry>, RouteEntry> routeSelector = null)
 {
     directRouteProvider = directRouteProvider ?? new DefaultDirectRouteProvider();
     var decorator = new DecoratorRouteProvider(directRouteProvider, routeSelector);
     configuration.MapHttpAttributeRoutes(decorator);
     var uriMakerContext = new UriMakerContext(decorator.RouteMap);
     configuration.Properties.AddOrUpdate(ContextKey, _ => uriMakerContext, (_, __) => uriMakerContext);
     return uriMakerContext;
 }
Beispiel #14
0
        public static UriMakerContext MapHttpAttributeRoutesAndUseUriMaker(
            this HttpConfiguration configuration,
            IDirectRouteProvider directRouteProvider = null,
            Func <HttpRequestMessage, ICollection <RouteEntry>, RouteEntry> routeSelector = null)
        {
            directRouteProvider = directRouteProvider ?? new DefaultDirectRouteProvider();
            var decorator = new DecoratorRouteProvider(directRouteProvider, routeSelector);

            configuration.MapHttpAttributeRoutes(decorator);
            var uriMakerContext = new UriMakerContext(decorator.RouteMap);

            configuration.Properties.AddOrUpdate(ContextKey, _ => uriMakerContext, (_, __) => uriMakerContext);
            return(uriMakerContext);
        }
        public static void MapAttributeRoutes(
            HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

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

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

            RouteCollectionRoute aggregateRoute = new RouteCollectionRoute();
            configuration.Routes.Add(AttributeRouteName, aggregateRoute);

            Action<HttpConfiguration> previousInitializer = configuration.Initializer;
            configuration.Initializer = config =>
                {
                    // Chain to the previous initializer hook. Do this before we access the config since
                    // initialization may make last minute changes to the configuration.
                    previousInitializer(config);

                    SubRouteCollection subRoutes = null;

                    // Add a single placeholder route that handles all of attribute routing.
                    // Add an initialize hook that initializes these routes after the config has been initialized.
                    Func<SubRouteCollection> initializer = () =>
                    {
                        subRoutes = new SubRouteCollection();
                        AddRouteEntries(subRoutes, configuration, constraintResolver, directRouteProvider);
                        return subRoutes;
                    };

                    // This won't change config. It wants to pick up the finalized config.
                    aggregateRoute.EnsureInitialized(initializer);

                    if (subRoutes != null)
                    {
                        AddGenerationHooksForSubRoutes(config.Routes, subRoutes.Entries);
                    }
                };
        }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes"></param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes.
        /// </param>
        public static void MapMvcAttributeRoutes(
            this RouteCollection routes,
            IDirectRouteProvider directRouteProvider)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

            AttributeRoutingMapper.MapAttributeRoutes(routes, new DefaultInlineConstraintResolver(), directRouteProvider);
        }
        private static HttpRouteEntry CreateRouteEntry(string routePrefix, IDirectRouteProvider provider,
                                                       IEnumerable <ReflectedHttpActionDescriptor> actions, IInlineConstraintResolver constraintResolver)
        {
            Contract.Assert(provider != null);

            DirectRouteProviderContext context = new DirectRouteProviderContext(routePrefix, actions,
                                                                                constraintResolver);
            HttpRouteEntry entry = provider.CreateRoute(context);

            if (entry == null)
            {
                throw Error.InvalidOperation(SRResources.TypeMethodMustNotReturnNull,
                                             typeof(IDirectRouteProvider).Name, "CreateRoute");
            }

            return(entry);
        }
        public void CreateRoute_IfBuilderContraintsIsNotNull_AddsConstraintsFromPropertyWhenBuilding()
        {
            // Arrange
            HttpRouteValueDictionary existingConstraints = new HttpRouteValueDictionary();
            string existingConstraintKey   = "ExistingContraintKey";
            object existingConstraintValue = "ExistingContraint";

            existingConstraints.Add(existingConstraintKey, existingConstraintValue);

            HttpRouteValueDictionary additionalConstraints = new HttpRouteValueDictionary();
            string additionalConstraintKey   = "NewConstraintKey";
            string additionalConstraintValue = "NewConstraint";

            additionalConstraints.Add(additionalConstraintKey, additionalConstraintValue);

            Mock <RouteProviderAttribute> productMock = CreateProductUnderTestMock();

            productMock.SetupGet(p => p.Constraints).Returns(additionalConstraints);
            IDirectRouteProvider product = productMock.Object;

            HttpRouteEntry expectedEntry = CreateEntry();

            HttpRouteValueDictionary constraints = null;
            DirectRouteBuilder       builder     = null;

            builder = CreateBuilder(() =>
            {
                constraints = builder.Constraints;
                return(null);
            });

            builder.Constraints = existingConstraints;

            DirectRouteProviderContext context = CreateContext((i) => builder);

            // Act
            HttpRouteEntry ignore = product.CreateRoute(context);

            // Assert
            Assert.Same(existingConstraints, constraints);
            Assert.Equal(2, constraints.Count);
            Assert.True(constraints.ContainsKey(existingConstraintKey));
            Assert.Same(existingConstraintValue, constraints[existingConstraintKey]);
            Assert.True(constraints.ContainsKey(additionalConstraintKey));
            Assert.Same(additionalConstraintValue, constraints[additionalConstraintKey]);
        }
        public void CreateRoute_DelegatesToContextCreateBuilderBuild()
        {
            // Arrange
            string expectedTemplate      = "RouteTemplate";
            IDirectRouteProvider product = CreateProductUnderTest(expectedTemplate);

            HttpRouteEntry expectedEntry = CreateEntry();

            DirectRouteBuilder         builder = CreateBuilder(() => expectedEntry);
            DirectRouteProviderContext context = CreateContext((template) =>
                                                               template == expectedTemplate ? builder : new DirectRouteBuilder(new ReflectedHttpActionDescriptor[0]));

            // Act
            HttpRouteEntry entry = product.CreateRoute(context);

            // Assert
            Assert.Same(expectedEntry, entry);
        }
        public void MapAttributeRoutes(RouteCollection routes, IEnumerable <Type> controllers, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
        {
            var mapMvcAttributeRoutesMethod = GetMapRoutesMethod();

            mapMvcAttributeRoutesMethod.Invoke(null, new object[] { routes, controllers, constraintResolver, routeProvider });
        }
 public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Type type, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
 {
     MapAttributeRoutesInAssembly(routes, type.Assembly, constraintResolver, routeProvider);
 }
        internal static void AddRouteEntries(SubRouteCollection collector, IEnumerable<Type> controllerTypes,
            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
        {
            IEnumerable<ReflectedAsyncControllerDescriptor> controllers = GetControllerDescriptors(controllerTypes);

            foreach (ReflectedAsyncControllerDescriptor controller in controllers)
            {
                List<ActionDescriptor> actions = GetActionDescriptors(controller);

                IReadOnlyCollection<RouteEntry> entries = directRouteProvider.GetDirectRoutes(controller, actions, constraintResolver);
                if (entries == null)
                {
                    throw Error.InvalidOperation(
                        MvcResources.TypeMethodMustNotReturnNull,
                        typeof(IDirectRouteProvider).Name, 
                        "GetDirectRoutes");
                }

                foreach (RouteEntry entry in entries)
                {
                    if (entry == null)
                    {
                        throw Error.InvalidOperation(
                            MvcResources.TypeMethodMustNotReturnNull,
                            typeof(IDirectRouteProvider).Name, 
                            "GetDirectRoutes");
                    }

                    DirectRouteBuilder.ValidateRouteEntry(entry);

                    // This marks the action/controller as unreachable via traditional routing.
                    if (entry.Route.GetTargetIsAction())
                    {
                        var actionDescriptors = entry.Route.GetTargetActionDescriptors();
                        Contract.Assert(actionDescriptors != null && actionDescriptors.Any());

                        foreach (var actionDescriptor in actionDescriptors.OfType<IMethodInfoActionDescriptor>())
                        {
                            var methodInfo = actionDescriptor.MethodInfo;
                            if (methodInfo != null)
                            {
                                controller.Selector.StandardRouteMethods.Remove(methodInfo);
                            }
                        }
                    }
                    else
                    {
                        // This is a controller-level route - no actions in this controller are reachable via
                        // traditional routes.
                        controller.Selector.StandardRouteMethods.Clear();
                    }
                }

                collector.AddRange(entries);
            }
        }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="controllerTypes">The controller types to scan.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes,
            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

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

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

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

            SubRouteCollection subRoutes = new SubRouteCollection();
            AddRouteEntries(subRoutes, controllerTypes, constraintResolver, directRouteProvider);
            IReadOnlyCollection<RouteEntry> entries = subRoutes.Entries;

            if (entries.Count > 0)
            {
                RouteCollectionRoute aggregrateRoute = new RouteCollectionRoute(subRoutes);
                routes.Add(aggregrateRoute);

                // This sort is here to enforce a static ordering for link generation using these routes. 
                // We don't apply dynamic criteria like ActionSelectors on link generation, but we can use the static
                // ones.
                //
                // Routes to actions are placed first because they are considered more specific. A route to an action
                // will only match for link generation if the action name was supplied, so this is essential for
                // correctness. Without this a controller-level route could be 'greedy' and generate a link when
                // the action-level route was intended.
                RouteEntry[] sorted = entries
                    .OrderBy(r => r.Route.GetOrder())
                    .ThenBy(r => r.Route.GetTargetIsAction() ? 0 : 1)
                    .ThenBy(r => r.Route.GetPrecedence())
                    .ToArray();

                AddGenerationHooksForSubRoutes(routes, sorted);
            }
        }
 public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Assembly assembly, IDirectRouteProvider routeProvider)
 {
     MapAttributeRoutesInAssembly(routes, assembly, new DefaultInlineConstraintResolver(), routeProvider);
 }
        public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Assembly assembly, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
        {
            var controllers = (assembly.GetExportedTypes()
                               .Where(IsControllerType)).ToList();

            MapAttributeRoutesInControllers(routes, controllers, constraintResolver, routeProvider);
        }
        public static void MapAttributeRoutesInControllers(this RouteCollection routes, IEnumerable <Type> controllers, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
        {
            var mvcAssemblyReflector = new MvcAssemblyReflector();

            mvcAssemblyReflector.MapAttributeRoutes(routes, controllers, constraintResolver, routeProvider);
        }
        internal static void AddRouteEntries(
            SubRouteCollection collector,
            IEnumerable <Type> controllerTypes,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider
            )
        {
            IEnumerable <ReflectedAsyncControllerDescriptor> controllers = GetControllerDescriptors(
                controllerTypes
                );

            foreach (ReflectedAsyncControllerDescriptor controller in controllers)
            {
                List <ActionDescriptor> actions = GetActionDescriptors(controller);

                IReadOnlyCollection <RouteEntry> entries = directRouteProvider.GetDirectRoutes(
                    controller,
                    actions,
                    constraintResolver
                    );
                if (entries == null)
                {
                    throw Error.InvalidOperation(
                              MvcResources.TypeMethodMustNotReturnNull,
                              typeof(IDirectRouteProvider).Name,
                              "GetDirectRoutes"
                              );
                }

                foreach (RouteEntry entry in entries)
                {
                    if (entry == null)
                    {
                        throw Error.InvalidOperation(
                                  MvcResources.TypeMethodMustNotReturnNull,
                                  typeof(IDirectRouteProvider).Name,
                                  "GetDirectRoutes"
                                  );
                    }

                    DirectRouteBuilder.ValidateRouteEntry(entry);

                    // This marks the action/controller as unreachable via traditional routing.
                    if (entry.Route.GetTargetIsAction())
                    {
                        var actionDescriptors = entry.Route.GetTargetActionDescriptors();
                        Contract.Assert(actionDescriptors != null && actionDescriptors.Any());

                        foreach (
                            var actionDescriptor in actionDescriptors.OfType <IMethodInfoActionDescriptor>()
                            )
                        {
                            var methodInfo = actionDescriptor.MethodInfo;
                            if (methodInfo != null)
                            {
                                controller.Selector.StandardRouteMethods.Remove(methodInfo);
                            }
                        }
                    }
                    else
                    {
                        // This is a controller-level route - no actions in this controller are reachable via
                        // traditional routes.
                        controller.Selector.StandardRouteMethods.Clear();
                    }
                }

                collector.AddRange(entries);
            }
        }
		public LocalizationDirectRouteProvider(IDirectRouteProvider directRouteProvider)
		{
			DirectRouteProvider = directRouteProvider;
			LocalizationCollectionRoutes = new List<RouteEntry>();
		}
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for discovering and building routes.
        /// </param>
        // Corresponds to the MVC implementation of attribute routing in
        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.
        public static void MapHttpAttributeRoutes(
            this HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

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

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

            AttributeRoutingMapper.MapAttributeRoutes(configuration, constraintResolver, directRouteProvider);
        }
        private static void AddRouteEntries(
            SubRouteCollection collector, 
            HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider)
        {
            Contract.Assert(configuration != null);
            Contract.Assert(directRouteProvider != null);

            IHttpControllerSelector controllerSelector = configuration.Services.GetHttpControllerSelector();
            IDictionary<string, HttpControllerDescriptor> controllerMap = controllerSelector.GetControllerMapping();
            if (controllerMap != null)
            {
                foreach (HttpControllerDescriptor controllerDescriptor in controllerMap.Values)
                {
                    IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector();

                    ILookup<string, HttpActionDescriptor> actionsByName =
                        actionSelector.GetActionMapping(controllerDescriptor);
                    if (actionsByName == null)
                    {
                        continue;
                    }

                    List<HttpActionDescriptor> actions = actionsByName.SelectMany(g => g).ToList();
                    IReadOnlyCollection<RouteEntry> newEntries =
                        directRouteProvider.GetDirectRoutes(controllerDescriptor, actions, constraintResolver);
                    if (newEntries == null)
                    {
                        throw Error.InvalidOperation(
                            SRResources.TypeMethodMustNotReturnNull,
                            typeof(IDirectRouteProvider).Name, "GetDirectRoutes");
                    }

                    foreach (RouteEntry entry in newEntries)
                    {
                        if (entry == null)
                        {
                            throw Error.InvalidOperation(
                                SRResources.TypeMethodMustNotReturnNull,
                                typeof(IDirectRouteProvider).Name, "GetDirectRoutes");
                        }

                        DirectRouteBuilder.ValidateRouteEntry(entry);

                        // We need to mark each action as only reachable by direct routes so that traditional routes
                        // don't accidentally hit them.
                        HttpControllerDescriptor routeControllerDescriptor = entry.Route.GetTargetControllerDescriptor();
                        if (routeControllerDescriptor == null)
                        {
                            HttpActionDescriptor[] actionDescriptors = entry.Route.GetTargetActionDescriptors();
                            foreach (var actionDescriptor in actionDescriptors)
                            {
                                actionDescriptor.SetIsAttributeRouted(true);
                            }
                        }
                        else
                        {
                            routeControllerDescriptor.SetIsAttributeRouted(true);
                        }                        
                    }

                    collector.AddRange(newEntries);
                }
            }
        }
 public static void MapAttributeRoutesInControllers(this RouteCollection routes, IEnumerable<Type> controllers, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
 {
     var mvcAssemblyReflector = new MvcAssemblyReflector();
     mvcAssemblyReflector.MapAttributeRoutes(routes, controllers, constraintResolver, routeProvider);
 }
		public void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllers, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
		{
			var mapMvcAttributeRoutesMethod = GetMapRoutesMethod();
			mapMvcAttributeRoutesMethod.Invoke(null, new object[] { routes, controllers, constraintResolver, routeProvider });
		}
Beispiel #33
0
 public LocalizationDirectRouteProvider(IDirectRouteProvider directRouteProvider)
 {
     DirectRouteProvider          = directRouteProvider;
     LocalizationCollectionRoutes = new List <RouteEntry>();
 }
        private static void AddRouteEntries(
            SubRouteCollection collector,
            HttpConfiguration configuration,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider)
        {
            Contract.Assert(configuration != null);
            Contract.Assert(directRouteProvider != null);

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

            if (controllerMap != null)
            {
                foreach (HttpControllerDescriptor controllerDescriptor in controllerMap.Values)
                {
                    IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector();

                    ILookup <string, HttpActionDescriptor> actionsByName =
                        actionSelector.GetActionMapping(controllerDescriptor);
                    if (actionsByName == null)
                    {
                        continue;
                    }

                    List <HttpActionDescriptor>      actions    = actionsByName.SelectMany(g => g).ToList();
                    IReadOnlyCollection <RouteEntry> newEntries =
                        directRouteProvider.GetDirectRoutes(controllerDescriptor, actions, constraintResolver);
                    if (newEntries == null)
                    {
                        throw Error.InvalidOperation(
                                  SRResources.TypeMethodMustNotReturnNull,
                                  typeof(IDirectRouteProvider).Name, "GetDirectRoutes");
                    }

                    foreach (RouteEntry entry in newEntries)
                    {
                        if (entry == null)
                        {
                            throw Error.InvalidOperation(
                                      SRResources.TypeMethodMustNotReturnNull,
                                      typeof(IDirectRouteProvider).Name, "GetDirectRoutes");
                        }

                        DirectRouteBuilder.ValidateRouteEntry(entry);

                        // We need to mark each action as only reachable by direct routes so that traditional routes
                        // don't accidentally hit them.
                        HttpControllerDescriptor routeControllerDescriptor = entry.Route.GetTargetControllerDescriptor();
                        if (routeControllerDescriptor == null)
                        {
                            HttpActionDescriptor[] actionDescriptors = entry.Route.GetTargetActionDescriptors();
                            foreach (var actionDescriptor in actionDescriptors)
                            {
                                actionDescriptor.SetIsAttributeRouted(true);
                            }
                        }
                        else
                        {
                            routeControllerDescriptor.SetIsAttributeRouted(true);
                        }
                    }

                    collector.AddRange(newEntries);
                }
            }
        }
 public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Type type, IInlineConstraintResolver constraintResolver, IDirectRouteProvider routeProvider)
 {
     MapAttributeRoutesInAssembly(routes, type.Assembly, constraintResolver, routeProvider);
 }
 public DecoratorRouteProvider(IDirectRouteProvider provider, Func<HttpRequestMessage, ICollection<RouteEntry>, RouteEntry> routeSelector = null)
 {
     _provider = provider;
     _routeSelector = routeSelector;
     RouteMap = methodInfo =>
     {
         MethodHandler entry;
         return _map.TryGetValue(methodInfo, out entry) ? entry : null;
     };
 }
 public static void MapAttributeRoutesInAssembly(this RouteCollection routes, Assembly assembly, IDirectRouteProvider routeProvider)
 {
     MapAttributeRoutesInAssembly(routes, assembly, new DefaultInlineConstraintResolver(), routeProvider);
 }