Beispiel #1
0
        public void Configure(IApplicationBuilder app, IInlineConstraintResolver resolver)
        {
            var defaultHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Route values: {string.Join(", ", routeValues)}"));
            });

            var routes = new RouteBuilder(app, defaultHandler);

            routes.MapGet("hello", (IApplicationBuilder app2) => {
                var routes2 = new RouteBuilder(app2);
                routes2.MapGet("world", (context) => context.Response.WriteAsync("Hello World"));
                app2.UseRouter(routes2.Build());
            });

            routes.MapRoute(
                name: "Default",
                template: "{*path}"
                );

            IRouter routing = routes.Build();

            app.UseRouter(routing);
        }
 public ScriptHandler(MemoryProcess process, KeyHandler keyHandler, RouteHandler routeHandler)
 {
     actionEvents      = new List <ActionEvent>();
     this.process      = process;
     this.keyHandler   = keyHandler;
     this.routeHandler = routeHandler;
 }
Beispiel #3
0
        public static IRouter GetRouterMiddleware(IApplicationBuilder app)
        {
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync(
                           $"Hello! Route values: {string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

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

            routeBuilder.MapGet("hello/{name}", context =>
            {
                var name = context.GetRouteValue("name");
                // The route handler when HTTP GET "hello/<anything>" matches
                // To match HTTP GET "hello/<anything>/<anything>,
                // use routeBuilder.MapGet("hello/{*name}"
                return(context.Response.WriteAsync($"Hi, {name}!"));
            });

            var routes = routeBuilder.Build();

            return(routes);
        }
Beispiel #4
0
 public void initalize(MemoryProcess process)
 {
     this.process  = process;
     keyHandler    = new KeyHandler(this.process);
     routeHandler  = new RouteHandler(this.process, this.keyHandler);
     scriptHandler = new ScriptHandler(this.process, this.keyHandler, this.routeHandler);
 }
Beispiel #5
0
 public Route(HttpRequestMethod method, string path, RouteHandler handler)
 {
     this.Method   = method;
     this.Path     = path;
     this.Handler  = handler;
     this.Segments = Router.ParseRoutePath(path);
 }
Beispiel #6
0
        private void AddDefaultHandlerForParameterizedAction(RouteHandler routes, MethodInfo info)
        {
            ParameterizedAction       action = ParameterizedActionFactory.CreateAction(info);
            ParameterizedActionTarget target = new ParameterizedActionTarget(this, info, action);

            AddImplicitRouteHandler(target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods);
        }
Beispiel #7
0
        public void Configure(IApplicationBuilder app)
        {
            var handler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                var path        = context.Request.Path;
                if (path == "/products/books")
                {
                    context.Response.Headers.Add("Content-Type", "application/json");
                    var books = File.ReadAllText("books.json");
                    return(context.Response.WriteAsync(books));
                }

                context.Response.Headers.Add("Content-Type", "text/html;charset=utf-8");
                return(context.Response.WriteAsync(
                           $@" 
                    <html>
					<body>
                    <h2>Selam Patron! Bugün nasılsın?</h2>
					{DateTime.Now.ToString()}
                    <ul>
                        <li><a href='/products/books'>Senin için bir kaç kitabım var. Haydi tıkla.</a></li>
						<li><a href='https://github.com/buraksenyurt'>Bu ve diğer .Net Core örneklerine bakmak istersen Git!</a></li>
                    </ul>                     
                    </body>
					</html>
                    "));
            });

            app.UseRouter(handler);
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseSession();
            app.UseAuthentication();    // подключение аутентификации
            app.UseAuthorization();
            var myRouteHandler = new RouteHandler(Handler);
            var routeBuilder   = new RouteBuilder(app, myRouteHandler);

            routeBuilder.MapRoute("default", "Home/Index/NextPage");
            app.UseRouter(routeBuilder.Build());
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void Configure(IApplicationBuilder app)
        {
            var defaultHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Route values: {string.Join(", ", routeValues)}"));
            });

            var routes = new RouteBuilder(app, defaultHandler);

            routes.MapRoute(
                name: "hello1",
                template: "hello/{greetings}/from/{country}"
                );

            routes.MapRoute(
                name: "hello2",
                template: "hello/{greetings}"
                );

            routes.MapRoute(
                name: "Default",
                template: "{*path}"
                );
            app.UseRouter(routes.Build());
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseStaticFiles();
            //app.UseAuthentication();
            app.UseMvc();
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync(
                           $"Hello! Route values: {string.Join(", ", routeValues)}"));
            });

            //var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);
            //routeBuilder.MapRoute("Answer Route", "Answer/Create/{id:int}");

            app.UseAuthentication();
            app.UseMvc();
        }
Beispiel #11
0
        public async Task UseRouteTemplateWithConstrainedPathComponentForDefaultHandler()
        {
            var builder = new WebHostBuilder()
                          .ConfigureLogging(setup =>
            {
                setup.AddDebug();
                setup.SetupDemoLogging(_testOutputHelper);
            })
                          .ConfigureServices(services =>
            {
                services.AddRouting();
            })
                          .Configure(app =>
            {
                var defaultHandler = new RouteHandler(context =>
                {
                    var name = context.GetRouteValue("name");
                    return(context.Response.WriteAsync($"Hello, {name}!"));
                });
                var routeBuilder = new RouteBuilder(app, defaultHandler);
                routeBuilder.MapRoute("default", "/test/{name:alpha}");
                var router = routeBuilder.Build();
                app.UseRouter(router);
            });

            var server = new TestServer(builder);

            var client = server.CreateClient();

            var response = await client.GetAsync("/test/1");

            Assert.Equal(StatusCodes.Status404NotFound, (int)response.StatusCode);
        }
Beispiel #12
0
        public async Task UseSimpleHandler()
        {
            var builder = new WebHostBuilder()
                          .ConfigureLogging(setup =>
            {
                setup.AddDebug();
                setup.SetupDemoLogging(_testOutputHelper);
            })
                          .ConfigureServices(services =>
            {
                services.AddRouting();
            })
                          .Configure(app =>
            {
                var router = new RouteHandler(context =>
                {
                    return(context.Response.WriteAsync("Hello, World!"));
                });
                app.UseRouter(router);
            });

            var server = new TestServer(builder);

            var client = server.CreateClient();

            var response = await client.GetAsync("/etst?name=World");

            var greeting = await response.Content.ReadAsStringAsync();

            Assert.Equal(StatusCodes.Status200OK, (int)response.StatusCode);
            Assert.Equal("Hello, World!", greeting);
        }
Beispiel #13
0
        public void Configure(IApplicationBuilder app)
        {
            RouteHandler routeHandler = new RouteHandler(Handle);

            IRouteBuilder routeBuilder = new RouteBuilder(app, routeHandler);

            routeBuilder.MapRoute("def1",
                                  "{controller}/{action}/{id}",
                                  null,
                                  new { action = "test1" }
                                  );

            routeBuilder.MapRoute("def2",
                                  "{controller}/{action}/{id}",
                                  null,
                                  new { action = "test2", id = new BoolRouteConstraint() }
                                  );

            routeBuilder.MapGet("Get/{controller}/{action}/{id?}", Handle);
            routeBuilder.MapPost("Post/{controller}/{action}/{id?}", async x =>
            {
                //doesn't working, because it's post request
                await x.Response.WriteAsync(x.Request.Path.Value);
            });


            app.UseRouter(routeBuilder.Build());

            app.Run(async x =>
            {
                await x.Response.WriteAsync("Def page");
            });
        }
Beispiel #14
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var handler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                var path        = context.Request.Path;
                if (path == "/arkadaslar")
                {
                    context.Response.Headers.Add("Content-Type", "application/json");
                    var books = File.ReadAllText("friends.json");
                    return(context.Response.WriteAsync(books));
                }

                return(context.Response.WriteAsync(@"
                                <!DOCTYPE html>
                                <html lang=""tr"">
                                  <head>
                                    <meta charset=""UTF-8"" />
                                    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
                                    <meta http-equiv=""X-UA-Compatible"" content=""ie=edge"" />
                                    <title>Dursun Katar</title>
                                  </head>
                                  <body>
                                    <h1 style=""text-align: center;"">Hoş Geldin Dostum :)</h1>
                                  </body>
                                </html>
                               "));
            });

            app.UseRouter(handler);
        }
        private RouteHandler GetRouteHandler(string requestPath)
        {
            RouteHandler handler = null;

            this.routingTable.TryGetValue(requestPath, out handler);
            return(handler);
        }
Beispiel #16
0
        public static void BuildRoutes(IApplicationBuilder app)
        {
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync(
                           $"Hello! Route values: {string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

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

            routeBuilder.MapGet("hello/{name}", context =>
            {
                var name = context.GetRouteValue("name");
                // This is the route handler when HTTP GET "hello/<anything>"  matches
                // To match HTTP GET "hello/<anything>/<anything>,
                // use routeBuilder.MapGet("hello/{*name}"
                return(context.Response.WriteAsync($"Hi, {name}!"));
            });

            routeBuilder.MapRoute(
                "ViewWorkshop",
                "{workshopCode}/",
                new { controller = "Workshop", action = "GetByCode" }
                );

            var routes = routeBuilder.Build();

            app.UseRouter(routes);
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Hello! Route values: {string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

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

            routeBuilder.MapGet("what/{name}", context =>
            {
                var name = context.GetRouteValue("name");
                // This is the route handler when HTTP GET "hello/<anything>"  matches
                // To match HTTP GET "hello/<anything>/<anything>,
                // use routeBuilder.MapGet("hello/{*name}"
                return(context.Response.WriteAsync($"Hi, {name}!"));
            });

            var routes = routeBuilder.Build();

            app.UseRouter(routes);

            app.UseMvc();
        }
Beispiel #18
0
        public void Configure(IApplicationBuilder app)
        {
            var defaultHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Route values: {string.Join(", ", routeValues)}"));
            });

            var routes = new RouteBuilder(app, defaultHandler);

            //This maps
            // - /hello
            // - /hello/adam
            // - /hello/sasha
            //The ? means that the segement is optional
            routes.MapGet("hello/{name?}", (context) => {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Hello {routeValues["name"]}"));
            });

            //This maps
            // - /goodbye (name is assigned value 'bond'. Make sure there is no space between '=' and default value)
            // - /goodbye/xxxx
            //The '=' operator means default value
            routes.MapGet("goodbye/{name=bond}", (context) => {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Goodbye {routeValues["name"]}"));
            });

            routes.MapRoute(
                name: "Default",
                template: "{*path}"
                );
            app.UseRouter(routes.Build());
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc(builder => builder.MapRoute("defaultRoute",
                                                   "api/{controller=demo}/{action=gethello}"));

            var customRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Your route data: {string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, customRouteHandler);

            routeBuilder.MapGet("customRouter/{name}",
                                context =>
            {
                var name_1 = context.GetRouteValue("name");
                return(context.Response.WriteAsync($"Hi, {name_1}"));
            }
                                );

            var router = routeBuilder.Build();

            app.UseRouter(router);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //app.UseMvc();
            var apiRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync(
                           $"Hello! Route values: {string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, apiRouteHandler);

            routeBuilder.MapRoute(
                "Default API Route",
                "api/{controller}/{operation}");
            routeBuilder.MapRoute(
                "API Route",
                "api/{controller}/{operation}/{id:int}");

            routeBuilder.MapGet("status", context =>
            {
                return(context.Response.WriteAsync($"OK!"));
            });
            //app.Map("/status", HandleBranch);
            var routes = routeBuilder.Build();

            app.UseRouter(routes);
            app.UseMvcWithDefaultRoute();
        }
        public override void AddEndpoint(MatcherEndpoint endpoint)
        {
            var handler = new RouteHandler(c =>
            {
                var feature      = c.Features.Get <IEndpointFeature>();
                feature.Endpoint = endpoint;
                feature.Invoker  = MatcherEndpoint.EmptyInvoker;

                return(Task.CompletedTask);
            });

            // MatcherEndpoint.Values contains the default values parsed from the template
            // as well as those specified with a literal. We need to separate those
            // for legacy cases.
            var defaults = endpoint.Defaults;

            for (var i = 0; i < endpoint.ParsedTemplate.Parameters.Count; i++)
            {
                var parameter = endpoint.ParsedTemplate.Parameters[i];
                if (parameter.DefaultValue == null && defaults.ContainsKey(parameter.Name))
                {
                    throw new InvalidOperationException(
                              "The TreeRouter does not support non-inline default values.");
                }
            }

            _inner.MapInbound(
                handler,
                endpoint.ParsedTemplate,
                routeName: null,
                order: endpoint.Order);
        }
Beispiel #22
0
        public RoutingBenchmark()
        {
            var handler = new RouteHandler((next) => Task.FromResult <object>(null));

            var treeBuilder = new TreeRouteBuilder(
                NullLoggerFactory.Instance,
                new DefaultObjectPool <UriBuildingContext>(new UriBuilderContextPooledObjectPolicy()),
                new DefaultInlineConstraintResolver(new OptionsManager <RouteOptions>(new OptionsFactory <RouteOptions>(Enumerable.Empty <IConfigureOptions <RouteOptions> >(), Enumerable.Empty <IPostConfigureOptions <RouteOptions> >()))));

            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets/{id}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets/search/{term}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("admin/users/{id}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("admin/users/{id}/manage"), "default", 0);

            _treeRouter = treeBuilder.Build();

            _requests = new RequestEntry[NumberOfRequestTypes];

            _requests[0].HttpContext = new DefaultHttpContext();
            _requests[0].HttpContext.Request.Path = "/api/Widgets/5";
            _requests[0].IsMatch = true;
            _requests[0].Values  = new RouteValueDictionary(new { id = 5 });

            _requests[1].HttpContext = new DefaultHttpContext();
            _requests[1].HttpContext.Request.Path = "/admin/users/17/mAnage";
            _requests[1].IsMatch = true;
            _requests[1].Values  = new RouteValueDictionary(new { id = 17 });

            _requests[2].HttpContext = new DefaultHttpContext();
            _requests[2].HttpContext.Request.Path = "/api/Widgets/search/dldldldldld/ddld";
            _requests[2].IsMatch = false;
            _requests[2].Values  = new RouteValueDictionary();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                //routes.MapRoute(
                //    name: "default",
                //    template: "{controller=Home}/{action=Index}/{id?}");
            });
            var myRouteHandler = new RouteHandler(Handle);
            var routeBuilder   = new RouteBuilder(app, myRouteHandler);

            routeBuilder.MapRoute("default",
                                  "{controller}/{action}/{id?}",
                                  null,
                                  new { myConstraint = new UrlConstraint(HttpContext.RequestServices.GetService <IElementRepository>()) }
                                  );
        }
Beispiel #24
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            var myRouteHandler = new RouteHandler(Handle);
            var routeBuilder   = new RouteBuilder(app, myRouteHandler);

            routeBuilder.MapRoute("default", "{controller}/{action}");
            app.UseRouter(routeBuilder.Build());

            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
        /// <summary>
        /// Configures the function host, adding a catch-all route that then hands off to Menes to process the request.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to configure.</param>
        public void Configure(IApplicationBuilder app)
        {
            var openApiRouteHandler = new RouteHandler(
                async context =>
            {
                try
                {
                    IOpenApiHost <HttpRequest, IActionResult> handler = context.RequestServices.GetRequiredService <IOpenApiHost <HttpRequest, IActionResult> >();
                    IActionResult result = await handler.HandleRequestAsync(context.Request.Path, context.Request.Method, context.Request, context).ConfigureAwait(false);
                    var actionContext    = new ActionContext(context, context.GetRouteData(), new ActionDescriptor());
                    await result.ExecuteResultAsync(actionContext).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.ToString());
                }
            });

            var routeBuilder = new RouteBuilder(app, openApiRouteHandler);

            routeBuilder.MapRoute("CatchAll", "{*path}");
            IRouter router = routeBuilder.Build();

            app.UseRouter(router);
        }
Beispiel #26
0
        public RoutingBenchmark()
        {
            var handler = new RouteHandler((next) => Task.FromResult <object>(null));

            var treeBuilder = new TreeRouteBuilder(
                NullLoggerFactory.Instance,
                new RoutePatternBinderFactory(UrlEncoder.Default, new DefaultObjectPoolProvider()),
                new DefaultInlineConstraintResolver(Options.Create(new RouteOptions())));

            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets/{id}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("api/Widgets/search/{term}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("admin/users/{id}"), "default", 0);
            treeBuilder.MapInbound(handler, TemplateParser.Parse("admin/users/{id}/manage"), "default", 0);

            _treeRouter = treeBuilder.Build();

            _requests = new RequestEntry[NumberOfRequestTypes];

            _requests[0].HttpContext = new DefaultHttpContext();
            _requests[0].HttpContext.Request.Path = "/api/Widgets/5";
            _requests[0].IsMatch = true;
            _requests[0].Values  = new RouteValueDictionary(new { id = 5 });

            _requests[1].HttpContext = new DefaultHttpContext();
            _requests[1].HttpContext.Request.Path = "/admin/users/17/mAnage";
            _requests[1].IsMatch = true;
            _requests[1].Values  = new RouteValueDictionary(new { id = 17 });

            _requests[2].HttpContext = new DefaultHttpContext();
            _requests[2].HttpContext.Request.Path = "/api/Widgets/search/dldldldldld/ddld";
            _requests[2].IsMatch = false;
            _requests[2].Values  = new RouteValueDictionary();
        }
Beispiel #27
0
        public void Configure(IApplicationBuilder app)
        {
            var defaultHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                context.Response.Headers.Add("Content-Type", "text/html");
                return(context.Response.WriteAsync(
                           $@"
                    <html><head><body>
                    <h1>Routing</h1>
                    Click on the following links to see the changes
                    <ul>
                        <li><a href=""/try"">/try</a></li>
                        <li><a href=""/do/33"">/do/33</a></li>
                        <li><a href=""/values/11/again"">/values/11/again</a></li>
                    </ul> 
                    <br/>
                    Path: {context.Request.Path}. 
                    <br/>
                    <br/>
                    Route values from context.GetRouteData().Values: {string.Join(", ", routeValues)}
                    <br/>
                    Note:
                    <br/>
                    context.GetRouteData() returns nothing regardless what kind of path you are requesting, e.g. '/hello-x'
                    </body></html>
                    "));
            });

            app.UseRouter(defaultHandler);
        }
Beispiel #28
0
        private void AddHandlerForParameterizedAction(RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
        {
            ParameterizedAction       action = ParameterizedActionFactory.CreateAction(info);
            ParameterizedActionTarget target = new ParameterizedActionTarget(this, info, action);

            AddImplicitRouteHandler(target, att.Patterns, att.Methods);
        }
Beispiel #29
0
        //使用自定义路由
        private void UseMyRoute(IApplicationBuilder app)
        {
            var trackPkgRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Hello! Route values:{string.Join(", ", routeValues)}"));
            });

            var routeBuilder = new RouteBuilder(app, trackPkgRouteHandler);

            //
            routeBuilder.MapRoute(
                "Track Package Route",
                "package/{operation:regex(^(track|create|detonate)$)}/{id:int}"
                );
            //
            routeBuilder.MapGet("hello/{name}", context =>
            {
                var values = context.GetRouteData().Values;
                return(context.Response.WriteAsync($"Hi, {values["name"]}!"));
            });

            //build
            var routes = routeBuilder.Build();

            app.UseRouter(routes);

            //
            // URLGenerationTest(app,routes);
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSwagger(options =>
            {
            });
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Testing Api V1");
            });

            app.UseMvc(routes =>
            {
                var Api404Handler = new RouteHandler(context =>
                {
                    context.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
                    return(Task.CompletedTask);
                });
                routes.Routes.Add(new Route(Api404Handler, "api/{*url}", defaults: null, constraints: null, dataTokens: null, inlineConstraintResolver: routes.ApplicationBuilder.ApplicationServices.GetRequiredService <IInlineConstraintResolver>()));
                routes.MapRoute("AngularRoute", "{*url}", new { controller = "Angular", action = "Index" });
            });
        }
        public static void Add(this RouteCollection routes, FalcorMethod method,
            IReadOnlyList<PathMatcher> pathMatchers, RouteHandler handler)
        {
            var route = handler
                .ToRoute()
                .MatchAndBindParameters(pathMatchers)
                .ForMethod(method);

            routes.Add(route);
        }
Beispiel #32
0
        SingleRoute IHttpServer.AddRoute(string path, IBlController controller, RouteHandler handler)
        {
            var route = add_route(new SingleRoute
                {
                    Path = path,
                    Controller = controller,
                    Handler = handler
                });

            return route;
        }
Beispiel #33
0
        public void Find_PartialMatchAtBeginningOfChildlessHandler_ReturnsProperRoute()
        {
            var rh_bad = new RouteHandler ("foo", "GET", new ActionTarget (FakeAction));
            var rh_good = new RouteHandler ("foobar", "GET", new ActionTarget (FakeAction2));
            var rh = new RouteHandler ();

            rh.Children.Add (rh_bad);
            rh.Children.Add (rh_good);

            var request = new MockHttpRequest ("GET", "foobar");
            var res = rh.Find (request);

            Assert.AreEqual (rh_good.Target, res);
        }
Beispiel #34
0
        public void HasPatternsTest()
        {
            var rh = new RouteHandler ("foo", "GET");

            Assert.IsTrue (rh.HasPatterns, "a1");

            rh.Patterns.Clear ();
            Assert.IsFalse (rh.HasPatterns, "a2");

            rh.Patterns.Add ("foobar");
            Assert.IsTrue (rh.HasPatterns, "a3");

            rh.Patterns = null;
            Assert.IsFalse (rh.HasPatterns, "a4");
        }
Beispiel #35
0
        public void Find_PartialMatchAtBeginningOfHandlerWithChildren_ReturnsProperRoute()
        {
            var rh_bad = new RouteHandler ("foo", HttpMethod.HTTP_GET);
            var rh_good = new RouteHandler ("foobar", HttpMethod.HTTP_GET, new ActionTarget (FakeAction2));
            var rh = new RouteHandler ();

            rh_bad.Children.Add (new RouteHandler ("blah", HttpMethod.HTTP_GET, new ActionTarget (FakeAction)));

            rh.Children.Add (rh_bad);
            rh.Children.Add (rh_good);

            var request = new MockHttpRequest (HttpMethod.HTTP_GET, "foobar");
            var res = rh.Find (request);

            Assert.AreEqual (rh_good.Target, res);
        }
Beispiel #36
0
        public void Find_PartialMatchAtBeginningOfChildlessHandler_ReturnsProperRoute()
        {
            IMatchOperation fooOp = MatchOperationFactory.Create("foo", MatchType.String);
            IMatchOperation foobarOp = MatchOperationFactory.Create("foobar", MatchType.String);
            var rh_bad = new RouteHandler(fooOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction));
            var rh_good = new RouteHandler(foobarOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction2));
            var rh = new RouteHandler();

            rh.Add(rh_bad);
            rh.Add(rh_good);

            var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foobar");
            IManosTarget res = rh.Find(request);

            Assert.AreEqual(rh_good.Target, res);
        }
Beispiel #37
0
        // Routes must configured in Configure
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;
                return context.Response.WriteAsync(
                    $"Hello! Route values: {string.Join(", ", routeValues)}");
            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

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

            routeBuilder.MapGet("hello/{name}", context =>
            {
                var name = context.GetRouteValue("name");
                // This is the route handler when HTTP GET "hello/<anything>"  matches
                // To match HTTP GET "hello/<anything>/<anything>, 
                // use routeBuilder.MapGet("hello/{*name}"
                return context.Response.WriteAsync($"Hi, {name}!");
            });            

            var routes = routeBuilder.Build();
            app.UseRouter(routes);

            // Show link generation when no routes match.
            app.Run(async (context) =>
            {
                var dictionary = new RouteValueDictionary
                {
                    { "operation", "create" },
                    { "id", 123}
                };

                var vpc = new VirtualPathContext(context, null, dictionary, "Track Package Route");
                var path = routes.GetVirtualPath(vpc).VirtualPath;

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("Menu<hr/>");
                await context.Response.WriteAsync($"<a href='{path}'>Create Package 123</a><br/>");
            });
            // End of app.Run
        }
Beispiel #38
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.Trace);

            var defaultHandler = new RouteHandler((c) => 
                c.Response.WriteAsync($"Hello world! Route values: " +
                $"{string.Join(", ", c.GetRouteData().Values)}")
                );

            var routeBuilder = new RouteBuilder(app, defaultHandler);

            routeBuilder.AddHelloRoute(app);

            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/>");
            });
        }
Beispiel #39
0
        public void TestChangePatterns()
        {
            //
            // Ensure that changing the patterns property works.
            // This is a bit of an edge case because internally
            // the patterns strings are cached as an array of
            // regexes.
            //

            var target = new MockManosTarget ();
            var rh = new RouteHandler ("^foo", "GET", target);
            var request = new MockHttpRequest ("GET", "foo");

            Assert.AreEqual (target, rh.Find (request), "sanity-1");

            rh.Patterns [0] = "baz";
            Assert.IsNull (rh.Find (request), "sanity-2");

            request = new MockHttpRequest ("GET", "baz");
            Assert.AreEqual (target, rh.Find (request), "changed");
        }
 public static void Add(this RouteCollection routes, FalcorMethod method, string path, RouteHandler handler) =>
     Add(routes, method, RouteParser.Parse(path), handler);
Beispiel #41
0
        public void UriParamsTestDeep()
        {
            var rh = new RouteHandler ("(?<animal>.+)/", "GET") {
                new RouteHandler ("(?<name>.+)", "GET", new ActionTarget (FakeAction)),
            };
            var request = new MockHttpRequest ("GET", "dog/roxy");

            Should.NotBeNull (rh.Find (request), "target");

            Should.NotBeNull (request.UriData, "uri-data");

            Assert.AreEqual ("dog", request.UriData ["animal"]);
            Assert.AreEqual ("roxy", request.UriData ["name"]);
        }
Beispiel #42
0
        public void UriParamsTest()
        {
            var rh = new RouteHandler ("(?<name>.+)", "GET", new ActionTarget (FakeAction));
            var request = new MockHttpRequest ("GET", "hello");

            Should.NotBeNull (rh.Find (request), "target");

            Should.NotBeNull (request.UriData, "uri-data");

            Assert.AreEqual ("hello", request.UriData ["name"]);
        }
Beispiel #43
0
        private void AddDefaultHandlerForParameterizedAction(RouteHandler routes, MethodInfo info)
        {
            ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
            ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);

            AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
        }
Beispiel #44
0
        /// <summary>
        /// Gets the instance of route handler.
        /// </summary>
        /// <param name="route">The route.</param>
        /// <returns>IRouteHandler</returns>
        private static IRouteHandler GetInstanceOfRouteHandler(RouteConfigElement route)
        {
            IRouteHandler routeHandler;

            if(IsDebugEnabled)
                log.Debug("route={0}", route);

            if(route.RouteHandlerType.IsWhiteSpace())
                routeHandler = new RouteHandler<Page>(route.VirtualPath, true);
            else
            {
                try
                {
                    Type routeHandlerType = Type.GetType(route.RouteHandlerType);

                    if(IsDebugEnabled)
                        log.Debug("route={0}, routeHandlerType={1}", route, routeHandlerType);

                    routeHandler = Activator.CreateInstance(routeHandlerType) as IRouteHandler;
                }
                catch(Exception e)
                {
                    throw new ApplicationException(string.Format("Can't create an instance of IRouteHandler {0}", route.RouteHandlerType), e);
                }
            }

            if(IsDebugEnabled)
                log.Debug("route={0}, routeHandler={1}", route, routeHandler);

            return routeHandler;
        }
Beispiel #45
0
        private void AddHandlerForAction(RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
        {
            ManosAction action = ActionForMethod (info);

            ActionTarget target = new ActionTarget (action);
             	AddImplicitRouteHandler (target, att.Patterns, att.Methods);
        }
Beispiel #46
0
        public void TestNoChildrenOfTarget()
        {
            var rh = new RouteHandler ("foo", HttpMethod.HTTP_GET, new ActionTarget (FakeAction));

            Should.Throw<InvalidOperationException> (() => rh.Children.Add (new RouteHandler ("foo", HttpMethod.HTTP_POST)));
        }
Beispiel #47
0
        private RouteHandler AddRouteHandler(IManosTarget target, string [] patterns, HttpMethod [] methods)
        {
            // TODO: Need to decide if this is a good or bad idea
            // RemoveImplicitHandlers (action);

            if (target == null)
                throw new ArgumentNullException ("action");
            if (patterns == null)
                throw new ArgumentNullException ("patterns");
            if (methods == null)
                throw new ArgumentNullException ("methods");

            RouteHandler res = new RouteHandler (SimpleOpsForPatterns (patterns), methods, target);
            Routes.Children.Add (res);
            return res;
        }
Beispiel #48
0
        private RouteHandler AddRouteHandler(IManosTarget target, IMatchOperation[] matchOperations, HttpMethod [] methods)
        {
            // TODO: Need to decide if this is a good or bad idea
            // RemoveImplicitHandlers (action);

            if (target == null)
                throw new ArgumentNullException ("action");
            if (matchOperations == null)
                throw new ArgumentNullException ("matchOperations");
            if (methods == null)
                throw new ArgumentNullException ("methods");

            RouteHandler res = new RouteHandler (matchOperations, methods, target);
            Routes.Children.Add (res);
            return res;
        }
Beispiel #49
0
        private void AddParameterizedActionHandler(RouteHandler routes, MethodInfo info)
        {
            HttpMethodAttribute [] atts = (HttpMethodAttribute []) info.GetCustomAttributes (typeof (HttpMethodAttribute), false);

            if (atts.Length == 0) {
                AddDefaultHandlerForParameterizedAction (routes, info);
                return;
            }

            foreach (HttpMethodAttribute att in atts) {
                AddHandlerForParameterizedAction (routes, att, info);
            }
        }
Beispiel #50
0
        private RouteHandler AddImplicitRouteHandlerForTarget(IManosTarget target, IMatchOperation [] ops, HttpMethod [] methods)
        {
            RouteHandler res = new RouteHandler (ops, methods, target) {
                IsImplicit = true,
            };

            Routes.Children.Add (res);
            return res;
        }
Beispiel #51
0
        private void AddHandlerForParameterizedAction(RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
        {
            ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
            ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);

            AddImplicitRouteHandlerForTarget (target, att.Patterns, att.Methods, att.MatchType);
        }
Beispiel #52
0
        private void AddHandlerForAction(RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
        {
            ManosAction action = ActionForMethod (info);

            ActionTarget target = new ActionTarget (action);

            string[] patterns = null == att.Patterns ? new string [] { "/" + info.Name } : att.Patterns;

            AddImplicitRouteHandlerForTarget (target, OpsForPatterns (patterns, att.MatchType), att.Methods);
        }
Beispiel #53
0
        public void TestNoChildrenOfTarget()
        {
            var rh = new RouteHandler ("foo", "GET", new ActionTarget (FakeAction));

            Should.Throw<InvalidOperationException> (() => rh.Children.Add (new RouteHandler ("foo", "POST")));
        }
Beispiel #54
0
        /// <summary>
        /// Based on request URI, method, and headers; form an appropriate response and carry out necessary actions on the server
        /// </summary>
        private RSResponse GenerateResponse()
        {
            var handler = new RouteHandler(_request.HttpMethod);

            //ReServer (RS) response object
            // Class used to build the raw output
            // which will be fed into the HttpResponse OutputStream
            RSResponse rsResponse = new RSResponse();

            // Check authentication details and return early if not valid
            if (!rsRequest.IsAuthorised)
            {
                return new StatusCodeResponse(HttpStatusCode.Unauthorized);
            }

            // Check first whether it is a dir
            if (Directory.Exists(rsRequest.LocalPath))
            {
                Output.Write("Directory");

                // localPath is a directory:
                // Check it ends with a slash
                if (rsRequest.PathEndsInSlash)
                {
                    Output.Write("Getting default file");

                    // Folder root requested:
                    // Search configured list of default pages
                    // and perform correct action
                    rsResponse = handler.HandleDefaultFileRoute(rsRequest.LocalPath, rsRequest.AcceptTypes);
                }
                else
                {
                    // Re-target the request to the directory itself
                    // to give correct behaviour when child files are requested

                    Output.Write("    Lacks terminating slash; redirecting...");

                    _response.Redirect(_request.Url.AbsoluteUri + '/');
                    rsResponse = new RedirectionResponse();
                }

            }
            else
            {
                //Return the requested file
                // or perform actions on it as a resource (depending on HttpMethod)
                rsResponse = handler.HandleFileRoute(rsRequest, _request.InputStream);

            }

            //If request was good and statuscode has not been assigned, assign 200
            if (rsResponse.Satisfied)
            {
                if ((int)rsResponse.StatusCode == 0)
                {
                    rsResponse.StatusCode = HttpStatusCode.OK;
                }
            }
            else
            {
                //If not found, return error or debug info
                //TODO change to 404 response?
                rsResponse = new TextResponse(rsRequest.Website.Local, _request, HttpStatusCode.NotFound);
            }

            //Convert the response to a client-preferred Content-Type
            // if it actually has content (i.e. not a redirect or error message)
            if (rsResponse.HasContent)
            {
                rsResponse = TryConvertToAcceptableContentType(rsResponse);
                _response.ContentType = rsResponse.ContentType.ToString();
            }

            /*
                Copy details to the real HTTP Response object
            */

            // Response code (if set)
            if (rsResponse.StatusCode != 0)
            {
                _response.StatusCode = (int)rsResponse.StatusCode;
            }

            // Additional headers added by the RSResponse
            if (rsResponse.AdditionalHeaders != null)
            {
                foreach (var h in rsResponse.AdditionalHeaders)
                {
                    _response.AppendHeader(h.Key, h.Value);
                }
            }

            return rsResponse;
        }
Beispiel #55
0
        private RouteHandler AddImplicitRouteHandler(IManosTarget target, string [] patterns, string [] methods)
        {
            RouteHandler res = new RouteHandler (patterns, methods, target) {
                IsImplicit = true,
            };

            Routes.Children.Add (res);
            return res;
        }
Beispiel #56
0
        public void TestSetPatternsNull()
        {
            var target = new MockManosTarget ();
            var rh = new RouteHandler ("^foo", "GET", target);
            var request = new MockHttpRequest ("GET", "foo");

            Assert.AreEqual (target, rh.Find (request), "sanity-1");

            rh.Patterns = null;

            Assert.IsNull (rh.Find (request), "is null");
        }
 public Route BuildRoute(RouteHandler handler, string path) =>
     handler.ToRoute()
     .MatchAndBindParameters(RouteParser.Parse(path))
     .ForMethod(_method);
Beispiel #58
0
        public void TestStrMatch()
        {
            var target = new MockManosTarget ();
            var rh = new RouteHandler ("^foo", "GET", target);
            var request = new MockHttpRequest ("GET", "foo");

            Assert.AreEqual (target, rh.Find (request), "should-match");

            request = new MockHttpRequest ("GET", "garbage-foo");
            Assert.IsNull (rh.Find (request), "garbage-input");
        }
Beispiel #59
0
        public void TestStrMatchDeep()
        {
            var target = new MockManosTarget ();
            var rh = new RouteHandler ("foo/", "GET") {
                new RouteHandler ("bar", "GET", target),
            };

            var request = new MockHttpRequest ("GET", "foo/bar");
            Assert.AreEqual (target, rh.Find (request));

            request = new MockHttpRequest ("GET", "foo/foo");
            Assert.IsNull (rh.Find (request), "repeate-input");

            request = new MockHttpRequest ("GET", "foo/badbar");
            Assert.IsNull (rh.Find (request), "matched-input");
        }
Beispiel #60
0
        private void AddDefaultHandlerForAction(RouteHandler routes, MethodInfo info)
        {
            ManosAction action = ActionForMethod (info);

            ActionTarget target = new ActionTarget (action);
            AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
        }