/// <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 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()));
        }
        /// <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 UseMvcXT(this IApplicationBuilder app, Action <IRouteBuilder> configureRoutes)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            // ... verify if AddMvcXT was done before calling UseMvcXT;
            // MvcXTMarkerService is here to make sure if all the services were added ...

            if (app.ApplicationServices.GetService(typeof(MvcXTMarkerService)) == null)
            {
                throw new InvalidOperationException(string.Format("You must call {{{0}}}.{{{1}}} in your '{2}' start up class method first for adding the CoreXT MVC pipeline.",
                                                                  nameof(IServiceCollection),
                                                                  "AddMvcXT",
                                                                  "ConfigureServices(...)"));
            }

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

            middlewarePipelineBuilder.ApplicationBuilder = app.New();                                               //?

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

            // ('MvcRouteHandler' is the default handler for mapping routes [i.e. routes.MapRoute()])

            configureRoutes?.Invoke(routes); // (note: if users call 'MapRoute()', it requires 'routes.DefaultHandler' to be set on the route builder)

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

            return(app.UseRouterXT(routes.Build()));
        }
Beispiel #3
0
        public static IApplicationBuilder UsePageContext(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("FormatUnableToFindServices" +
                                                    "AddMvc" +
                                                    "ConfigureServices(...)");
            }

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

            configureRoutes(routes);

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

            return(app.UseMiddleware <PageContextMiddleware>(routes.Build()));
        }
        /// <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.
            MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

            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()));
        }
Beispiel #5
0
        private static void PrepareApplicationAndRoutes(StartupMethods startupMethods)
        {
            var applicationBuilder = new MockedApplicationBuilder(serviceProvider);

            startupMethods?.ConfigureDelegate?.Invoke(applicationBuilder);

            AdditionalApplicationConfiguration?.Invoke(applicationBuilder);

            var routeBuilder = new RouteBuilder(applicationBuilder)
            {
                DefaultHandler = new RouteHandler(NullHandler)
            };

            for (int i = 0; i < applicationBuilder.Routes.Count; i++)
            {
                var route = applicationBuilder.Routes[i];
                routeBuilder.Routes.Add(route);
            }

            AdditionalRoutes?.Invoke(routeBuilder);

            if (StartupType == null || routeBuilder.Routes.Count == 0)
            {
                routeBuilder.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routeBuilder.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
                                               routeBuilder.DefaultHandler,
                                               serviceProvider));
            }

            router = routeBuilder.Build();
        }
Beispiel #6
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;

            // Create the IRouter if not yet created.
            // Done here rather than at startup so that order doesn't matter in ConfigureServices.
            if (router == null)
            {
                var rb = new MultiTenantRouteBuilder(MultiTenantMiddleware.ApplicationServices);
                // Apply explicit routes.
                configRoutes(rb);
                // Insert attribute based routes.
                rb.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(MultiTenantMiddleware.ApplicationServices));

                router = rb.Build();
            }

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

            object identifier = null;

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

            return(identifier as string);
        }
    public async Task AttributeRouting_MultipleErrors()
    {
        // Arrange
        var action1 = CreateAction("DisallowedParameter1", "{foo}/{action}");

        action1.RouteValues.Add("foo", "bleh");

        var action2 = CreateAction("DisallowedParameter2", "cool/{action}");

        action2.RouteValues.Add("action", "hey");

        var expectedMessage =
            "The following errors occurred with attribute routing information:" + Environment.NewLine +
            Environment.NewLine +
            "For action: 'DisallowedParameter1'" + Environment.NewLine +
            "Error: The attribute route '{foo}/{action}' cannot contain a parameter named '{foo}'. " +
            "Use '[foo]' in the route template to insert the value 'bleh'." + Environment.NewLine +
            Environment.NewLine +
            "For action: 'DisallowedParameter2'" + Environment.NewLine +
            "Error: The attribute route 'cool/{action}' cannot contain a parameter named '{action}'. " +
            "Use '[action]' in the route template to insert the value 'hey'.";

        var services = CreateServices(action1, action2);

        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);
    }
    public async Task AttributeRouting_SyntaxErrorInTemplate()
    {
        // Arrange
        var value  = "a/dkfk";
        var action = CreateAction("InvalidTemplate", "{" + value + "}");

        var expectedMessage =
            "The following errors occurred with attribute routing information:" + Environment.NewLine +
            Environment.NewLine +
            "For action: 'InvalidTemplate'" + Environment.NewLine +
            "Error: The route parameter name 'a/dkfk' is invalid. Route parameter names must be non-empty and " +
            "cannot contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, " +
            "and can occur only at the end of the parameter. The '*' character marks a parameter as catch-all, " +
            "and can occur only at the start of the parameter. (Parameter 'routeTemplate')";

        var services = CreateServices(action);

        var route        = AttributeRouting.CreateAttributeMegaRoute(services);
        var routeContext = new RouteContext(new DefaultHttpContext());

        // Act & Assert
        var ex = await Assert.ThrowsAsync <RouteCreationException>(() => route.RouteAsync(routeContext));

        Assert.Equal(expectedMessage, ex.Message);
    }
Beispiel #9
0
        private static IRouter GenerateRouter(IApplicationBuilder applicationBuilder)
        {
            var routes = new RouteBuilder(applicationBuilder)
            {
                DefaultHandler = applicationBuilder.ApplicationServices.GetRequiredService <MvcRouteHandler>()
            };

            routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(applicationBuilder.ApplicationServices));
            return(routes.Build());
        }
Beispiel #10
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 rb = new RouteBuilder(builder, new MultiTenantRouteHandler());

            configRoute(rb);

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

            var routes = rb.Build();

            return(builder.UseMiddleware <MultiTenantMiddleware>(routes));
        }
Beispiel #11
0
        public void Configure(IRouteBuilder builder)
        {
            builder.Routes.Add(new Route(
                                   builder.DefaultHandler,
                                   "Default",
                                   "{area:exists}/{controller}/{action}/{id?}",
                                   null,
                                   null,
                                   null,
                                   builder.ServiceProvider.GetService <IInlineConstraintResolver>())
                               );

            builder.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(builder.ServiceProvider));
        }
Beispiel #12
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()));
        }
Beispiel #13
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));
        }
        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));
        }
Beispiel #15
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));
        }
Beispiel #16
0
        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()));
        }
Beispiel #17
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);
        }
Beispiel #18
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()));
        }
        /// <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()));
        }
        /// <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()));
        }
        /// <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()));
        }
Beispiel #22
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);
    }
        // 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);
        }
Beispiel #24
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);
        }