Пример #1
0
        public void GetVirtualPath_CanLowerCaseUrls_And_AppendTrailingSlash_BasedOnOptions(
            string returnUrl,
            string expectedUrl,
            bool lowercaseUrls,
            bool appendTrailingSlash)
        {
            // Arrange
            var target = new Mock<IRouter>(MockBehavior.Strict);
            target
                .Setup(e => e.GetVirtualPath(It.IsAny<VirtualPathContext>()))
                .Returns(new VirtualPathData(target.Object, returnUrl));

            var routeCollection = new RouteCollection();
            routeCollection.Add(target.Object);
            var virtualPathContext = CreateVirtualPathContext(
                options: GetRouteOptions(
                    lowerCaseUrls: lowercaseUrls,
                    useBestEffortLinkGeneration: true,
                    appendTrailingSlash: appendTrailingSlash));

            // Act
            var pathData = routeCollection.GetVirtualPath(virtualPathContext);

            // Assert
            Assert.Equal(new PathString(expectedUrl), pathData.VirtualPath);
            Assert.Same(target.Object, pathData.Router);
            Assert.Empty(pathData.DataTokens);
        }
        public IRouter Build() {
            var routeCollection = new RouteCollection();

            foreach (var route in Routes) {
                routeCollection.Add(route);
            }

            return routeCollection;
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
            app.UseIISPlatformHandler();

            var routeBuilder = new RouteBuilder();
            routeBuilder.ServiceProvider = app.ApplicationServices;

            routeBuilder.Routes.Add(new TemplateRoute(
                new HelloRouter(),
                "hello/{name:alpha}",
                app.ApplicationServices.GetService<IInlineConstraintResolver>()));

            var endpoint1 = new DelegateRouter(async (context) =>
                            await context
                                .HttpContext
                                .Response
                                .WriteAsync("Hello world! Route Values: " +
                                    string.Join("", context.RouteData.Values)));

            routeBuilder.DefaultHandler = endpoint1;

            routeBuilder.MapRoute(
                "Track Package Route",
                "package/{operation:regex(track|create|detonate)}/{id:int}");

            app.UseRouter(routeBuilder.Build());

            // demonstrate link generation
            var trackingRouteCollection = new RouteCollection();
            trackingRouteCollection.Add(routeBuilder.Routes[1]); // "Track Package Route"

            app.Run(async (context) =>
            {
                var dictionary = new RouteValueDictionary
                {
                    {"operation","create" },
                    {"id",123}
                };

                var vpc = new VirtualPathContext(context,
                    null, dictionary, "Track Package Route");

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("Menu<hr/>");
                await context.Response.WriteAsync(@"<a href='" +
                    trackingRouteCollection.GetVirtualPath(vpc).VirtualPath +
                    "'>Create Package 123</a><br/>");
            });
        }
Пример #4
0
        public static void EnableSerenity(this IApplicationBuilder app, IHostingEnvironment env, IConfiguration config, ILoggerFactory loggerFactory)
        {
            var serenityConfiguration = config.GetConfigurationSection("Serenity");
            if (serenityConfiguration == null) return;

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new SerenityFileProvider(env, serenityConfiguration.Get("WebAppName")),
                ContentTypeProvider = new RazorContentTypeProvider()
            });

            string fallbackToServerConfig;
            var fallbackToServer = serenityConfiguration.TryGet("StaticFiles:FallbackToServer", out fallbackToServerConfig) && Convert.ToBoolean(fallbackToServerConfig);
            var proxyRouteHandler = new ProxyRouteHandler(serenityConfiguration.Get("RenderingHost"), Dns.GetHostName(), fallbackToServer);

            var routeCollection = new RouteCollection();
            routeCollection.Add(new TemplateRoute(proxyRouteHandler, "{*catchall}", null));
            app.UseRouter(routeCollection);
        }
Пример #5
0
        public void GetVirtualPath_DoesntLowerCaseUrls_Invariant(
            string returnUrl,
            string lowercaseUrl,
            bool lowercaseUrls)
        {
            // Arrange
            var target = new Mock<IRouter>(MockBehavior.Strict);
            target
                .Setup(e => e.GetVirtualPath(It.IsAny<VirtualPathContext>()))
                .Returns(new VirtualPathData(target.Object, returnUrl));

            var routeCollection = new RouteCollection();
            routeCollection.Add(target.Object);
            var virtualPathContext = CreateVirtualPathContext(options: GetRouteOptions(lowercaseUrls));

            // Act
            var pathData = routeCollection.GetVirtualPath(virtualPathContext);

            // Assert
            Assert.Equal(new PathString(lowercaseUrl), pathData.VirtualPath);
            Assert.Same(target.Object, pathData.Router);
            Assert.Empty(pathData.DataTokens);
        }
Пример #6
0
        public void GetVirtualPath_ReturnsDataTokens(RouteValueDictionary dataTokens, string routerName)
        {
            // Arrange
            var virtualPath = new PathString("/TestVirtualPath");

            var pathContextValues = new RouteValueDictionary { { "controller", virtualPath } };

            var pathContext = CreateVirtualPathContext(
                pathContextValues,
                GetRouteOptions(),
                routerName);

            var route = CreateTemplateRoute("{controller}", routerName, dataTokens);
            var routeCollection = new RouteCollection();
            routeCollection.Add(route);

            var expectedDataTokens = dataTokens ?? new RouteValueDictionary();

            // Act
            var pathData = routeCollection.GetVirtualPath(pathContext);

            // Assert
            Assert.NotNull(pathData);
            Assert.Same(route, pathData.Router);

            Assert.Equal(virtualPath, pathData.VirtualPath);

            Assert.Equal(expectedDataTokens.Count, pathData.DataTokens.Count);
            foreach (var dataToken in expectedDataTokens)
            {
                Assert.True(pathData.DataTokens.ContainsKey(dataToken.Key));
                Assert.Equal(dataToken.Value, pathData.DataTokens[dataToken.Key]);
            }
        }
Пример #7
0
        private static RouteCollection GetNestedRouteCollection(string[] routeNames)
        {
            var random = new Random();
            int index = random.Next(0, routeNames.Length - 1);
            var first = routeNames.Take(index).ToArray();
            var second = routeNames.Skip(index).ToArray();

            var rc1 = GetRouteCollectionWithNamedRoutes(first);
            var rc2 = GetRouteCollectionWithNamedRoutes(second);
            var rc3 = new RouteCollection();
            var rc4 = new RouteCollection();

            rc1.Add(rc3);
            rc4.Add(rc2);

            // Add a few unnamedRoutes.
            rc1.Add(CreateRoute(accept: false).Object);
            rc2.Add(CreateRoute(accept: false).Object);
            rc3.Add(CreateRoute(accept: false).Object);
            rc3.Add(CreateRoute(accept: false).Object);
            rc4.Add(CreateRoute(accept: false).Object);
            rc4.Add(CreateRoute(accept: false).Object);

            var routeCollection = new RouteCollection();
            routeCollection.Add(rc1);
            routeCollection.Add(rc4);

            return routeCollection;
        }
Пример #8
0
        private static RouteCollection GetRouteCollectionWithNamedRoutes(IEnumerable<string> routeNames)
        {
            var routes = new RouteCollection();
            foreach (var routeName in routeNames)
            {
                var route1 = CreateNamedRoute(routeName, accept: true);
                routes.Add(route1);
            }

            return routes;
        }
Пример #9
0
        private static async Task<TestSink> SetUp(bool enabled, bool handled)
        {
            // Arrange
            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouteCollection>,
                TestSink.EnableWithTypeName<RouteCollection>);
            var loggerFactory = new TestLoggerFactory(sink, enabled);

            var routes = new RouteCollection();
            var route = CreateRoute(accept: handled);
            routes.Add(route.Object);

            var context = CreateRouteContext("/Cool", loggerFactory);

            // Act
            await routes.RouteAsync(context);

            return sink;
        }
Пример #10
0
        public void GetVirtualPath_Success(
            string template,
            RouteValueDictionary values,
            string expectedUrl,
            bool lowercaseUrls
            )
        {
            // Arrange
            var routeCollection = new RouteCollection();
            var route = CreateTemplateRoute(template);
            routeCollection.Add(route);
            var context = CreateVirtualPathContext(values, options: GetRouteOptions(lowercaseUrls));

            // Act
            var pathData = routeCollection.GetVirtualPath(context);

            // Assert
            Assert.True(context.IsBound);
            Assert.Equal(new PathString(expectedUrl), pathData.VirtualPath);
            Assert.Same(route, pathData.Router);
            Assert.Empty(pathData.DataTokens);
        }
Пример #11
0
        public void GetVirtualPath_BestEffort_FirstValidatedValuesWins_Nested()
        {
            // Arrange
            var route1 = CreateRoute(accept: false, match: true, matchValue: "bad");
            var route2 = CreateRoute(accept: false, match: true, matchValue: "bad");
            var route3 = CreateRoute(accept: true, match: true, matchValue: "best");

            var routeCollection = new RouteCollection();
            routeCollection.Add(route1.Object);

            var innerRouteCollection = new RouteCollection();
            innerRouteCollection.Add(route2.Object);
            innerRouteCollection.Add(route3.Object);
            routeCollection.Add(innerRouteCollection);

            var options = new RouteOptions()
            {
                UseBestEffortLinkGeneration = true,
            };

            var virtualPathContext = CreateVirtualPathContext(options: options);

            // Act
            var pathData = routeCollection.GetVirtualPath(virtualPathContext);

            Assert.Equal(new PathString("/best"), pathData.VirtualPath);
            Assert.Same(route3.Object, pathData.Router);
            Assert.Empty(pathData.DataTokens);

            // All of these should be called
            route1.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
            route2.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
            route3.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
        }
Пример #12
0
        public void GetVirtualPath_NoBestEffort_NoMatch()
        {
            // Arrange
            var route1 = CreateRoute(accept: false, match: true, matchValue: "best");
            var route2 = CreateRoute(accept: false, match: true, matchValue: "bad");
            var route3 = CreateRoute(accept: false, match: true, matchValue: "bad");

            var routeCollection = new RouteCollection();
            routeCollection.Add(route1.Object);
            routeCollection.Add(route2.Object);
            routeCollection.Add(route3.Object);

            var options = new RouteOptions()
            {
                UseBestEffortLinkGeneration = false,
            };

            var virtualPathContext = CreateVirtualPathContext(options: options);

            // Act
            var path = routeCollection.GetVirtualPath(virtualPathContext);

            Assert.Null(path);

            // All of these should be called
            route1.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
            route2.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
            route3.Verify(r => r.GetVirtualPath(It.IsAny<VirtualPathContext>()), Times.Once());
        }
Пример #13
0
        public void GetVirtualPath_NamedRoute_BestEffort_FirstRouteWins()
        {
            // Arrange
            var bestMatch = CreateNamedRoute("Match", accept: false, matchValue: "best");
            var noMatch = CreateNamedRoute("NoMatch", accept: false, matchValue: "bad");

            var routeCollection = new RouteCollection();
            routeCollection.Add(noMatch);

            var innerRouteCollection = new RouteCollection();
            innerRouteCollection.Add(bestMatch);
            routeCollection.Add(innerRouteCollection);

            var options = new RouteOptions()
            {
                UseBestEffortLinkGeneration = true,
            };

            var virtualPathContext = CreateVirtualPathContext("Match", options: options);

            // Act
            var pathData = routeCollection.GetVirtualPath(virtualPathContext);

            Assert.Equal(new PathString("/best"), pathData.VirtualPath);
            var namedRouter = Assert.IsAssignableFrom<INamedRouter>(pathData.Router);
            Assert.Equal("Match", namedRouter.Name);
            Assert.Empty(pathData.DataTokens);
        }
Пример #14
0
        public void GetVirtualPath_AmbiguousRoutes_RequiresRouteValueValidation_Error()
        {
            // Arrange
            var namedRoute = CreateNamedRoute("Ambiguous", accept: false);

            var routeCollection = new RouteCollection();
            routeCollection.Add(namedRoute);

            var innerRouteCollection = new RouteCollection();
            innerRouteCollection.Add(namedRoute);
            routeCollection.Add(innerRouteCollection);

            var options = new RouteOptions()
            {
                UseBestEffortLinkGeneration = true,
            };

            var virtualPathContext = CreateVirtualPathContext("Ambiguous", options: options);

            // Act & Assert
            var ex = Assert.Throws<InvalidOperationException>(() => routeCollection.GetVirtualPath(virtualPathContext));
            Assert.Equal("The supplied route name 'Ambiguous' is ambiguous and matched more than one route.", ex.Message);
        }
Пример #15
0
        public async Task RouteAsync_NoMatch()
        {
            // Arrange
            var routes = new RouteCollection();
            var route1 = CreateRoute(accept: false);
            routes.Add(route1.Object);

            var route2 = CreateRoute(accept: false);
            routes.Add(route2.Object);

            var context = CreateRouteContext("/Cool");

            // Act
            await routes.RouteAsync(context);

            // Assert
            route1.Verify(e => e.RouteAsync(It.IsAny<RouteContext>()), Times.Exactly(1));
            route2.Verify(e => e.RouteAsync(It.IsAny<RouteContext>()), Times.Exactly(1));
            Assert.False(context.IsHandled);

            Assert.Empty(context.RouteData.Routers);
        }
Пример #16
0
        public async Task RouteAsync_SecondMatches()
        {
            // Arrange

            var routes = new RouteCollection();
            var route1 = CreateRoute(accept: false);
            routes.Add(route1.Object);

            var route2 = CreateRoute(accept: true);
            routes.Add(route2.Object);

            var context = CreateRouteContext("/Cool");

            // Act
            await routes.RouteAsync(context);

            // Assert
            route1.Verify(e => e.RouteAsync(It.IsAny<RouteContext>()), Times.Exactly(1));
            route2.Verify(e => e.RouteAsync(It.IsAny<RouteContext>()), Times.Exactly(1));
            Assert.True(context.IsHandled);

            Assert.Equal(1, context.RouteData.Routers.Count);
            Assert.Same(route2.Object, context.RouteData.Routers[0]);
        }