public async Task UseRouter_Action_CallsRoute()
        {
            // Arrange
            var services = CreateServices();

            var app = new ApplicationBuilder(services);

            var router = new Mock <IRouter>(MockBehavior.Strict);

            router
            .Setup(r => r.RouteAsync(It.IsAny <RouteContext>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            app.UseRouter(b =>
            {
                b.Routes.Add(router.Object);
            });

            var appFunc = app.Build();

            // Act
            await appFunc(new DefaultHttpContext());

            // Assert
            router.Verify();
        }
        public async Task UseRouting_ServicesRegistered_Match_DoesNotSetsFeature()
        {
            // Arrange
            var endpoint = new RouteEndpoint(
                TestConstants.EmptyRequestDelegate,
                RoutePatternFactory.Parse("{*p}"),
                0,
                EndpointMetadataCollection.Empty,
                "Test");

            var services = CreateServices();

            var app = new ApplicationBuilder(services);

            app.UseRouting(builder =>
            {
                builder.DataSources.Add(new DefaultEndpointDataSource(endpoint));
            });

            var appFunc     = app.Build();
            var httpContext = new DefaultHttpContext();

            // Act
            await appFunc(httpContext);

            // Assert
            var feature = httpContext.Features.Get <IEndpointFeature>();

            Assert.NotNull(feature);
            Assert.Same(endpoint, feature.Endpoint);
        }
Beispiel #3
0
        public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource()
        {
            // Arrange
            var matcherEndpointDataSources = new List <EndpointDataSource>();
            var matcherFactoryMock         = new Mock <MatcherFactory>();

            matcherFactoryMock
            .Setup(m => m.CreateMatcher(It.IsAny <EndpointDataSource>()))
            .Callback((EndpointDataSource arg) =>
            {
                matcherEndpointDataSources.Add(arg);
            })
            .Returns(new TestMatcher(false));

            var services = CreateServices(matcherFactoryMock.Object);

            var app = new ApplicationBuilder(services);

            // Act
            app.UseRouting();
            app.UseEndpoints(builder =>
            {
                builder.Map("/1", d => null).WithDisplayName("Test endpoint 1");
                builder.Map("/2", d => null).WithDisplayName("Test endpoint 2");
            });

            app.UseRouting();
            app.UseEndpoints(builder =>
            {
                builder.Map("/3", d => null).WithDisplayName("Test endpoint 3");
                builder.Map("/4", d => null).WithDisplayName("Test endpoint 4");
            });

            // This triggers the middleware to be created and the matcher factory to be called
            // with the datasource we want to test
            var requestDelegate = app.Build();

            requestDelegate(new DefaultHttpContext());

            // Assert
            Assert.Equal(2, matcherEndpointDataSources.Count);

            // each UseRouter has its own data source collection
            Assert.Collection(matcherEndpointDataSources[0].Endpoints,
                              e => Assert.Equal("Test endpoint 1", e.DisplayName),
                              e => Assert.Equal("Test endpoint 2", e.DisplayName));

            Assert.Collection(matcherEndpointDataSources[1].Endpoints,
                              e => Assert.Equal("Test endpoint 3", e.DisplayName),
                              e => Assert.Equal("Test endpoint 4", e.DisplayName));

            var compositeEndpointBuilder = services.GetRequiredService <EndpointDataSource>();

            // Global collection has all endpoints
            Assert.Collection(compositeEndpointBuilder.Endpoints,
                              e => Assert.Equal("Test endpoint 1", e.DisplayName),
                              e => Assert.Equal("Test endpoint 2", e.DisplayName),
                              e => Assert.Equal("Test endpoint 3", e.DisplayName),
                              e => Assert.Equal("Test endpoint 4", e.DisplayName));
        }
        public async Task UseEndpointExecutor_RunsEndpoint()
        {
            // Arrange
            var services = CreateServices();

            var endpointRan = false;
            var app         = new ApplicationBuilder(services);

            app.Use(next => context =>
            {
                context.SetEndpoint(new Endpoint(c =>
                {
                    endpointRan = true;
                    return(Task.CompletedTask);
                }, new EndpointMetadataCollection(), "Test"));
                return(next(context));
            });

            app.UseEndpointExecutor(); // No services required, no UseRouting required

            var appFunc     = app.Build();
            var httpContext = new DefaultHttpContext();

            // Act
            await appFunc(httpContext);

            // Assert
            Assert.True(endpointRan);
        }
Beispiel #5
0
        public static IApplicationBuilder UseBuilder(this AddMiddleware app, IServiceProvider serviceProvider)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            // Do not set ApplicationBuilder.ApplicationServices to null. May fail later due to missing services but
            // at least that results in a more useful Exception than a NRE.
            if (serviceProvider == null)
            {
                serviceProvider = new EmptyProvider();
            }

            // Adapt WebSockets by default.
            app(OwinWebSocketAcceptAdapter.AdaptWebSockets);
            var builder = new ApplicationBuilder(serviceProvider: serviceProvider);

            var middleware = CreateMiddlewareFactory(exit =>
            {
                builder.Use(ignored => exit);
                return(builder.Build());
            }, builder.ApplicationServices);

            app(middleware);
            return(builder);
        }
Beispiel #6
0
        public void UseEndpoints_WithGlobalEndpointRouteBuilderHasRoutes()
        {
            // Arrange
            var services = CreateServices();

            var app = new ApplicationBuilder(services);

            var mockRouteBuilder = new Mock <IEndpointRouteBuilder>();

            mockRouteBuilder.Setup(m => m.DataSources).Returns(new List <EndpointDataSource>());

            var routeBuilder = mockRouteBuilder.Object;

            app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder);
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/1", d => Task.CompletedTask).WithDisplayName("Test endpoint 1");
            });

            var requestDelegate = app.Build();

            var endpointDataSource = Assert.Single(mockRouteBuilder.Object.DataSources);

            Assert.Collection(endpointDataSource.Endpoints,
                              e => Assert.Equal("Test endpoint 1", e.DisplayName));

            var routeOptions = app.ApplicationServices.GetRequiredService <IOptions <RouteOptions> >();

            Assert.Equal(mockRouteBuilder.Object.DataSources, routeOptions.Value.EndpointDataSources);
        }
        public async Task UseRouting_ServicesRegistered_NoMatch_DoesNotSetFeature()
        {
            // Arrange
            var services = CreateServices();

            var app = new ApplicationBuilder(services);

            app.UseRouting(builder => { });

            var appFunc     = app.Build();
            var httpContext = new DefaultHttpContext();

            // Act
            await appFunc(httpContext);

            // Assert
            Assert.Null(httpContext.Features.Get <IEndpointFeature>());
        }
        public async Task UseEndpoint_ServicesRegisteredAndEndpointRoutingRegistered_SetsFeature()
        {
            // Arrange
            var services = CreateServices();

            var app = new ApplicationBuilder(services);

            app.UseEndpointRouting();
            app.UseEndpoint();

            var appFunc     = app.Build();
            var httpContext = new DefaultHttpContext();

            // Act
            await appFunc(httpContext);

            // Assert
            Assert.NotNull(httpContext.Features.Get <IEndpointFeature>());
        }
Beispiel #9
0
        /// <summary>
        /// Creates a new isolated application builder which gets its own <see cref="ServiceCollection"/>, which only
        /// has the default services registered. It will not share the <see cref="ServiceCollection"/> from the
        /// originating app.
        /// </summary>
        /// <param name="app">The application builder to create the isolated app from.</param>
        /// <param name="configuration">The branch of the isolated app.</param>
        /// <param name="registration">A method to configure the newly created service collection.</param>
        /// <returns>The new pipeline with the isolated application integrated.</returns>
        public static IApplicationBuilder Isolate(
            this IApplicationBuilder app,
            Action <IApplicationBuilder> configuration,
            Func <IServiceCollection, IServiceProvider> registration)
        {
            var services = CreateDefaultServiceCollection(app.ApplicationServices);
            var provider = registration(services);

            var builder = new ApplicationBuilder(null);

            builder.ApplicationServices = provider;

            builder.Use(async(context, next) =>
            {
                var factory = provider.GetRequiredService <IServiceScopeFactory>();

                // Store the original request services in the current ASP.NET context.
                context.Items[typeof(IServiceProvider)] = context.RequestServices;

                try
                {
                    using (var scope = factory.CreateScope())
                    {
                        context.RequestServices = scope.ServiceProvider;

                        await next();
                    }
                }

                finally
                {
                    context.RequestServices = null;
                }
            });

            configuration(builder);

            return(app.Use(next =>
            {
                // Run the rest of the pipeline in the original context,
                // with the services defined by the parent application builder.
                builder.Run(async context =>
                {
                    var factory = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>();

                    try
                    {
                        using (var scope = factory.CreateScope())
                        {
                            context.RequestServices = scope.ServiceProvider;

                            await next(context);
                        }
                    }

                    finally
                    {
                        context.RequestServices = null;
                    }
                });

                var branch = builder.Build();

                return context => branch(context);
            }));
        }