Example #1
0
        public async Task Invoke_LogsCorrectValues_WhenNotHandled()
        {
            // Arrange
            var expectedMessage = "Request did not match any routes";
            var isHandled       = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();

            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router     = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            var write = Assert.Single(sink.Writes);

            Assert.Equal(expectedMessage, write.State?.ToString());
        }
Example #2
0
        public async Task Invoke_DoesNotLog_WhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();

            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router     = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Empty(sink.Writes);
        }
Example #3
0
        public async void Invoke_DoesNotLog_WhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Empty(sink.Writes);
        }
Example #4
0
        public async void Invoke_DoesNotLogWhenDisabledAndNotHandled()
        {
            // Arrange
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: false);

            var httpContext = new DefaultHttpContext();

            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices     = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router     = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, httpContext.ApplicationServices, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Empty(sink.Writes);
        }
Example #5
0
        public async void Invoke_LogsCorrectValues_WhenNotHandled()
        {
            // Arrange
            var expectedMessage = "Request did not match any routes.";
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Example #6
0
        private static async Task ReExecuteAsync(HttpContext context)
        {
            IRouter router = context.GetRouteData().Routers[0];

            RouterMiddleware routerMiddleware = new RouterMiddleware(_ => Task.CompletedTask, context.RequestServices.GetRequiredService <ILoggerFactory>(), router);

            await routerMiddleware.Invoke(context);
        }
Example #7
0
        public async void Invoke_LogsCorrectValuesWhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var mockContext = new Mock <HttpContext>(MockBehavior.Strict);

            mockContext.Setup(m => m.RequestServices.GetService(typeof(ILoggerFactory)))
            .Returns(loggerFactory);

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router = new TestRouter(isHandled);
            var mockServiceProvider = new Mock <IServiceProvider>();
            var middleware          = new RouterMiddleware(next, mockServiceProvider.Object, router);

            // Act
            await middleware.Invoke(mockContext.Object);

            // Assert
            // exists a BeginScope, verify contents
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Single(sink.Writes);

            var write = sink.Writes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, write.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", write.Scope);
            Assert.Equal(typeof(RouterMiddlewareInvokeValues), write.State.GetType());
            var values = (RouterMiddlewareInvokeValues)write.State;

            Assert.Equal("RouterMiddleware.Invoke", values.Name);
            Assert.Equal(true, values.Handled);
        }
Example #8
0
        public async void Invoke_LogsCorrectValuesWhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();

            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices     = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router = new TestRouter(isHandled);

            var middleware = new RouterMiddleware(next, httpContext.ApplicationServices, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            // exists a BeginScope, verify contents
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Single(sink.Writes);

            var write = sink.Writes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, write.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", write.Scope);
            Assert.Equal(typeof(RouterMiddlewareInvokeValues), write.State.GetType());
            var values = (RouterMiddlewareInvokeValues)write.State;

            Assert.Equal("RouterMiddleware.Invoke", values.Name);
            Assert.Equal(true, values.Handled);
        }
Example #9
0
        public async Task RoutingFeatureSetInIRouter()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddLogging();
            var httpContext = new DefaultHttpContext
            {
                RequestServices = services.BuildServiceProvider()
            };

            httpContext.Request.Path = "/foo/10";

            var routeHandlerExecuted = false;

            var handler = new RouteHandler(context =>
            {
                routeHandlerExecuted = true;

                var routingFeature = context.Features.Get <IRoutingFeature>();

                Assert.NotNull(routingFeature);
                Assert.NotNull(context.Features.Get <IRouteValuesFeature>());

                Assert.Single(routingFeature.RouteData.Values);
                Assert.Single(context.Request.RouteValues);
                Assert.True(routingFeature.RouteData.Values.ContainsKey("id"));
                Assert.True(context.Request.RouteValues.ContainsKey("id"));
                Assert.Equal("10", routingFeature.RouteData.Values["id"]);
                Assert.Equal("10", context.Request.RouteValues["id"]);
                Assert.Equal("10", context.GetRouteValue("id"));
                Assert.Same(routingFeature.RouteData, context.GetRouteData());

                return(Task.CompletedTask);
            });

            var route = new Route(handler, "/foo/{id}", Mock.Of <IInlineConstraintResolver>());

            var middleware = new RouterMiddleware(context => Task.CompletedTask, NullLoggerFactory.Instance, route);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.True(routeHandlerExecuted);
        }
Example #10
0
        /// <summary>
        /// To use the CoreXT main router properly, this should be the only handler in the whole pipeline.
        /// </summary>
        /// <param name="httpContext">The context of the incoming request.</param>
        /// <returns>A task to handle this request.</returns>
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await _RouterMiddleware.Invoke(httpContext);
            }
            catch (HttpException httpException)
            {
                httpContext.Response.StatusCode = httpException.StatusCode;
                var responseFeature = httpContext.Features.Get <IHttpResponseFeature>();
                responseFeature.ReasonPhrase = httpException.Message;
            }

            //// ... build a context for this request ...

            //var context = new RouteContext(httpContext);
            //context.RouteData.Routers.Add(_Router); // (add the root level RouteCollection router, which will cascade the request down other nested routers to find matches)

            //// ... attempt to route using the context just created for this request; on failure to find a match, the handler will be null ...

            //await _Router.RouteAsync(context);

            //if (context.Handler == null)
            //{
            //    _Logger.LogDebug(1, "Request did not match any routes on the main routing middleware.");
            //    // ... did not find a match ... hand it off to the encapsulated standard MVC middleware ...
            //    await _RouterMiddleware.Invoke(httpContext);
            //}
            //else
            //{
            //    httpContext.Features[typeof(IRoutingFeature)] = new RoutingFeature()
            //    {
            //        RouteData = context.RouteData,
            //    };

            //    await context.Handler(context.HttpContext);
            //}
        }
Example #11
0
        public async void Invoke_DoesNotLogWhenDisabledAndNotHandled()
        {
            // Arrange
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName <RouterMiddleware>,
                TestSink.EnableWithTypeName <RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: false);

            var mockContext = new Mock <HttpContext>(MockBehavior.Strict);

            mockContext.Setup(m => m.RequestServices.GetService(typeof(ILoggerFactory)))
            .Returns(loggerFactory);

            RequestDelegate next = (c) =>
            {
                return(Task.FromResult <object>(null));
            };

            var router = new TestRouter(isHandled);
            var mockServiceProvider = new Mock <IServiceProvider>();
            var middleware          = new RouterMiddleware(next, mockServiceProvider.Object, router);

            // Act
            await middleware.Invoke(mockContext.Object);

            // Assert
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];

            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Empty(sink.Writes);
        }