コード例 #1
0
        /// <summary>
        /// Use Finbuckle.MultiTenant middleware with routing support in processing the request.
        /// </summary>
        /// <param name="builder">The <c>IApplicationBuilder<c/> instance the extension method applies to.</param>
        /// <returns>The same <c>IApplicationBuilder</c> passed into the method.</returns>
        public static IApplicationBuilder UseMultiTenant(this IApplicationBuilder builder, Action <IRouteBuilder> configRoute)
        {
            var routeHandler = new RouteHandler(context => null);
            var rb           = new RouteBuilder(builder, routeHandler);

            configRoute(rb);

            // insert attribute based routes
            rb.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(builder.ApplicationServices));

            var routes = rb.Build();

            return(builder.UseMiddleware <MultiTenantMiddleware>(routes));
        }
コード例 #2
0
        public static IBuilder UseMvc([NotNull] this IBuilder app, [NotNull] Action <IRouteBuilder> configureRoutes)
        {
            var routes = new RouteBuilder
            {
                DefaultHandler  = new MvcRouteHandler(),
                ServiceProvider = app.ApplicationServices
            };

            routes.Routes.Add(AttributeRouting.CreateAttributeMegaRoute(
                                  routes.DefaultHandler,
                                  app.ApplicationServices));

            configureRoutes(routes);

            return(app.UseRouter(routes.Build()));
        }
コード例 #3
0
        public void Configure(IRouteBuilder builder)
        {
            var inlineConstraintResolver = _serviceProvider.GetService <IInlineConstraintResolver>();

            // The default route is added to each tenant as a template route, with a prefix
            builder.Routes.Add(new Route(
                                   builder.DefaultHandler,
                                   "Default",
                                   "{area:exists}/{controller}/{action}/{id?}",
                                   null,
                                   null,
                                   null,
                                   inlineConstraintResolver)
                               );

            builder.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(_serviceProvider));
        }
コード例 #4
0
        public static IApplicationBuilder UseApiAuthorized(this IApplicationBuilder builder, Action <IRouteBuilder> configureRoutes)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            var routes = new RouteBuilder(builder)
            {
                DefaultHandler = builder.ApplicationServices.GetRequiredService <MvcRouteHandler>(),
            };

            configureRoutes(routes);
            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(builder.ApplicationServices));
            var router = routes.Build();

            return(builder.UseMiddleware <ApiAuthorizedMiddleware>(router));
        }
コード例 #5
0
        public static IApplicationBuilder UseGetRoutesMiddleware(this IApplicationBuilder app, Action <IRouteBuilder> configureRoutes)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var routes = new RouteBuilder(app)
            {
                DefaultHandler = app.ApplicationServices.GetRequiredService <MvcRouteHandler>(),
            };

            configureRoutes(routes);
            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
            var router = routes.Build();

            return(app.UseMiddleware <GetRoutesMiddleware>(router));
        }
コード例 #6
0
ファイル: DebbyAdmin.cs プロジェクト: anthrax3/debby.admin
        public static IApplicationBuilder UseDebby(
            this IApplicationBuilder app,
            Action <IRouteBuilder> configureRoutes)
        {
            MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

            var routes = new RouteBuilder
            {
                DefaultHandler  = new MvcRouteHandler(),
                ServiceProvider = app.ApplicationServices
            };

            routes.Routes.Add(AttributeRouting.CreateAttributeMegaRoute(
                                  routes.DefaultHandler,
                                  app.ApplicationServices));

            configureRoutes(routes);

            return(app.UseRouter(routes.Build()));
        }
コード例 #7
0
        public async Task <string> GetIdentifierAsync(object context)
        {
            if (!(context is HttpContext))
            {
                throw new MultiTenantException(null,
                                               new ArgumentException($"\"{nameof(context)}\" type must be of type HttpContext", nameof(context)));
            }

            var httpContext = context as HttpContext;

            // Detect if app model changed (eg Razor Pages file update)
            if (actionDescriptorsVersion != actionDescriptorCollectionProvider.ActionDescriptors.Version)
            {
                actionDescriptorsVersion = actionDescriptorCollectionProvider.ActionDescriptors.Version;
                router = null;
            }

            // Create the IRouter if not yet created.
            if (router == null)
            {
                var rb = new MultiTenantRouteBuilder(httpContext.RequestServices);
                // Apply explicit routes.
                configRoutes(rb);
                // Insert attribute based routes.
                rb.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(httpContext.RequestServices));

                router = rb.Build();
            }

            // Check the route.
            var routeContext = new RouteContext(httpContext);
            await router.RouteAsync(routeContext)
            .ConfigureAwait(false);

            object identifier = null;

            routeContext.RouteData?.Values.TryGetValue(tenantParam, out identifier);

            return(identifier as string);
        }
コード例 #8
0
        /// <summary>
        /// Adds MVC to the <see cref="IApplicationBuilder"/> request execution pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="configureRoutes">A callback to configure MVC routes.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseMvc(
            this IApplicationBuilder app,
            Action <IRouteBuilder> configureRoutes)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configureRoutes == null)
            {
                throw new ArgumentNullException(nameof(configureRoutes));
            }

            // Verify if AddMvc was done before calling UseMvc
            // We use the MvcMarkerService to make sure if all the services were added.
            if (app.ApplicationServices.GetService(typeof(MvcMarkerService)) == null)
            {
                throw new InvalidOperationException(Resources.FormatUnableToFindServices(
                                                        nameof(IServiceCollection),
                                                        "AddMvc",
                                                        "ConfigureServices(...)"));
            }

            var middlewarePipelineBuilder = app.ApplicationServices.GetRequiredService <MiddlewareFilterBuilder>();

            middlewarePipelineBuilder.ApplicationBuilder = app.New();

            var routes = new RouteBuilder(app)
            {
                DefaultHandler = app.ApplicationServices.GetRequiredService <MvcRouteHandler>(),
            };

            configureRoutes(routes);

            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));

            return(app.UseRouter(routes.Build()));
        }
コード例 #9
0
        /// <summary>
        /// Adds MVC to the <see cref="IApplicationBuilder"/> request execution pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="configureRoutes">A callback to configure MVC routes.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseMvc(
            this IApplicationBuilder app,
            Action <IRouteBuilder> configureRoutes)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configureRoutes == null)
            {
                throw new ArgumentNullException(nameof(configureRoutes));
            }

            // Verify if AddMvc was done before calling UseMvc
            // We use the MvcMarkerService to make sure if all the services were added.
            if (app.ApplicationServices.GetService(typeof(MvcMarkerService)) == null)
            {
                throw new InvalidOperationException(Resources.FormatUnableToFindServices(
                                                        nameof(IServiceCollection),
                                                        "AddMvc",
                                                        "ConfigureServices(...)"));
            }

            var routes = new RouteBuilder(app)
            {
                DefaultHandler = new MvcRouteHandler(),
            };

            configureRoutes(routes);

            // Adding the attribute route comes after running the user-code because
            // we want to respect any changes to the DefaultHandler.
            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
                                     routes.DefaultHandler,
                                     app.ApplicationServices));

            return(app.UseRouter(routes.Build()));
        }
コード例 #10
0
        public static IApplicationBuilder UseMvc(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action <IRouteBuilder> configureRoutes)
        {
            // Verify if AddMvc was done before calling UseMvc
            // We use the MvcMarkerService to make sure if all the services were added.
            MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

            var routes = new RouteBuilder
            {
                DefaultHandler  = new MvcRouteHandler(),
                ServiceProvider = app.ApplicationServices
            };

            routes.Routes.Add(AttributeRouting.CreateAttributeMegaRoute(
                                  routes.DefaultHandler,
                                  app.ApplicationServices));

            configureRoutes(routes);

            return(app.UseRouter(routes.Build()));
        }
コード例 #11
0
        /// <summary>
        /// Adds MVC to the <see cref="IApplicationBuilder"/> request execution pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="configureRoutes">A callback to configure MVC routes.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseMvc(
            this IApplicationBuilder app,
            Action <IRouteBuilder> configureRoutes)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configureRoutes == null)
            {
                throw new ArgumentNullException(nameof(configureRoutes));
            }

            VerifyMvcIsRegistered(app);

            var options = app.ApplicationServices.GetRequiredService <IOptions <MvcOptions> >();

            if (options.Value.EnableEndpointRouting)
            {
                var message =
                    "Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use " +
                    "'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside " +
                    "'ConfigureServices(...).";
                throw new InvalidOperationException(message);
            }

            var routes = new RouteBuilder(app)
            {
                DefaultHandler = app.ApplicationServices.GetRequiredService <MvcRouteHandler>(),
            };

            configureRoutes(routes);

            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));

            return(app.UseRouter(routes.Build()));
        }
コード例 #12
0
    public async Task AttributeRouting_WithControllerActionDescriptor()
    {
        // Arrange
        var controllerType = typeof(HomeController);
        var actionMethod   = controllerType.GetMethod("Index");

        var action = new ControllerActionDescriptor();

        action.DisplayName = "Microsoft.AspNetCore.Mvc.Routing.AttributeRoutingTest+HomeController.Index";
        action.MethodInfo  = actionMethod;
        action.RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
        {
            { "controller", "Home" },
            { "action", "Index" },
        };
        action.AttributeRouteInfo          = new AttributeRouteInfo();
        action.AttributeRouteInfo.Template = "{controller}/{action}";

        var expectedMessage =
            "The following errors occurred with attribute routing information:" + Environment.NewLine +
            Environment.NewLine +
            "For action: 'Microsoft.AspNetCore.Mvc.Routing.AttributeRoutingTest+HomeController.Index'" + Environment.NewLine +
            "Error: The attribute route '{controller}/{action}' cannot contain a parameter named '{controller}'. " +
            "Use '[controller]' in the route template to insert the value 'Home'.";

        var services = CreateServices(action);

        var route = AttributeRouting.CreateAttributeMegaRoute(services);

        // Act & Assert
        var ex = await Assert.ThrowsAsync <RouteCreationException>(async() =>
        {
            await route.RouteAsync(new RouteContext(new DefaultHttpContext()));
        });

        Assert.Equal(expectedMessage, ex.Message);
    }
コード例 #13
0
ファイル: BuilderExtensions.cs プロジェクト: rkakadia/Mvc-1
        /// <summary>
        /// Adds Mvc to the <see cref="IApplicationBuilder"/> request execution pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="configureRoutes">A callback to configure Mvc routes.</param>
        /// <returns>The <paramref name="app"/>.</returns>
        public static IApplicationBuilder UseMvc(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action <IRouteBuilder> configureRoutes)
        {
            // Verify if AddMvc was done before calling UseMvc
            // We use the MvcMarkerService to make sure if all the services were added.
            MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

            var routes = new RouteBuilder
            {
                DefaultHandler  = new MvcRouteHandler(),
                ServiceProvider = app.ApplicationServices
            };

            configureRoutes(routes);

            // Adding the attribute route comes after running the user-code because
            // we want to respect any changes to the DefaultHandler.
            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
                                     routes.DefaultHandler,
                                     app.ApplicationServices));

            return(app.UseRouter(routes.Build()));
        }
コード例 #14
0
        // Build the middleware pipeline for the current tenant
        public RequestDelegate BuildTenantPipeline(
            ShellSettings shellSettings,
            HttpContext httpContext)
        {
            var serviceProvider          = httpContext.RequestServices;
            var startUps                 = serviceProvider.GetServices <IStartup>();
            var inlineConstraintResolver = serviceProvider.GetService <IInlineConstraintResolver>();
            var appBuilder               = new ApplicationBuilder(serviceProvider);

            var routePrefix = "";

            if (!string.IsNullOrWhiteSpace(shellSettings.RequestedUrlPrefix))
            {
                routePrefix = shellSettings.RequestedUrlPrefix + "/";
            }

            var routeBuilder = new RouteBuilder(appBuilder)
            {
                DefaultHandler = serviceProvider.GetRequiredService <MvcRouteHandler>()
            };

            // Build prefixed route builder
            var prefixedRouteBuilder = new PrefixedRouteBuilder(
                routePrefix,
                routeBuilder,
                inlineConstraintResolver);

            // Configure modules
            foreach (var startup in startUps)
            {
                startup.Configure(appBuilder, prefixedRouteBuilder, serviceProvider);
            }

            // Add the default template route to each shell
            prefixedRouteBuilder.Routes.Add(new Route(
                                                prefixedRouteBuilder.DefaultHandler,
                                                "PlatoDefault",
                                                "{area:exists}/{controller}/{action}/{id?}",
                                                null,
                                                null,
                                                null,
                                                inlineConstraintResolver)
                                            );

            // Add attribute routing
            routeBuilder.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(serviceProvider));

            // Build router
            var router = prefixedRouteBuilder.Build();

            // Use router
            appBuilder.UseRouter(router);

            // Create a captured HttpContext for use outside of application context
            var capturedHttpContext = serviceProvider.GetService <ICapturedHttpContext>();

            capturedHttpContext.Configure(state => state.Contextualize(httpContext));

            // Create a captured router for use outside of application context
            var capturedRouter = serviceProvider.GetService <ICapturedRouter>();

            capturedRouter.Configure(options =>
            {
                options.Router  = router;
                options.BaseUrl = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}";
            });

            // Build & return new pipeline
            var pipeline = appBuilder.Build();

            return(pipeline);
        }
コード例 #15
0
        // Build the middleware pipeline for the current tenant
        public RequestDelegate BuildTenantPipeline(
            ShellSettings shellSettings,
            HttpContext httpContext)
        {
            var serviceProvider          = httpContext.RequestServices;
            var startUps                 = serviceProvider.GetServices <IStartup>();
            var inlineConstraintResolver = serviceProvider.GetService <IInlineConstraintResolver>();
            var appBuilder               = new ApplicationBuilder(serviceProvider);

            var routePrefix = "";

            if (!string.IsNullOrWhiteSpace(shellSettings.RequestedUrlPrefix))
            {
                routePrefix = shellSettings.RequestedUrlPrefix + "/";
            }

            var routeBuilder = new RouteBuilder(appBuilder)
            {
                DefaultHandler = serviceProvider.GetRequiredService <MvcRouteHandler>()
            };

            // Build prefixed route builder
            var prefixedRouteBuilder = new PrefixedRouteBuilder(
                routePrefix,
                routeBuilder,
                inlineConstraintResolver);

            // Configure modules
            foreach (var startup in startUps)
            {
                startup.Configure(appBuilder, prefixedRouteBuilder, serviceProvider);
            }

            //// Add the default template route to each shell
            prefixedRouteBuilder.Routes.Add(new Route(
                                                prefixedRouteBuilder.DefaultHandler,
                                                "PlatoDefault",
                                                "{area:exists}/{controller}/{action}/{id?}",
                                                null,
                                                null,
                                                null,
                                                inlineConstraintResolver)
                                            );

            // Add attribute routing
            routeBuilder.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(serviceProvider));

            // TODO: The homepage route is not set via the Plato.Core module
            // Attempt to get homepage route for tenant from site settings store
            // If the tenant has not been created yet siteService will return null
            // if siteService returns null users will be presented with the SetUp module
            ////var siteService = routeBuilder.ServiceProvider.GetService<ISiteSettingsStore>();
            ////if (siteService != null)
            ////{

            ////    //// Add the default template route to each shell
            ////    prefixedRouteBuilder.Routes.Add(new Route(
            ////        prefixedRouteBuilder.DefaultHandler,
            ////        "PlatoHome",
            ////        "",
            ////        new HomeRoute(),
            ////        null,
            ////        null,
            ////        inlineConstraintResolver)
            ////    );

            ////    // Add home page route matching
            ////    var homeRoute = new HomePageRoute(
            ////        shellSettings.RequestedUrlPrefix,
            ////        siteService,
            ////        routeBuilder,
            ////        inlineConstraintResolver);

            ////    routeBuilder.Routes.Add(homeRoute);

            ////}

            // ------------------

            // Build router
            var router = prefixedRouteBuilder.Build();

            // Use router
            appBuilder.UseRouter(router);

            // Create a captured HttpContext for use outside of application context
            var capturedHttpContext = serviceProvider.GetService <ICapturedHttpContext>();

            capturedHttpContext.Configure(state => state.Contextualize(httpContext));

            // Create a captured router for use outside of application context
            var capturedRouter = serviceProvider.GetService <ICapturedRouter>();

            capturedRouter.Configure(options =>
            {
                options.Router  = router;
                options.BaseUrl = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}";
            });

            // Build & return new pipeline
            var pipeline = appBuilder.Build();

            return(pipeline);
        }