当前位置: 首页>>代码示例>>C#>>正文


C# IApplicationBuilder.UseRouter方法代码示例

本文整理汇总了C#中IApplicationBuilder.UseRouter方法的典型用法代码示例。如果您正苦于以下问题:C# IApplicationBuilder.UseRouter方法的具体用法?C# IApplicationBuilder.UseRouter怎么用?C# IApplicationBuilder.UseRouter使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IApplicationBuilder的用法示例。


在下文中一共展示了IApplicationBuilder.UseRouter方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Configure

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            LifetimeManager lifetimeManager,
            InterpreterManager interpreterManager,
            SecurityManager securityManager
        ) {
            lifetimeManager.Initialize();
            interpreterManager.Initialize();

            app.UseWebSockets(new WebSocketOptions {
                ReplaceFeature = true,
                KeepAliveInterval = TimeSpan.FromMilliseconds(1000000000),
                ReceiveBufferSize = 0x10000
            });

            var routeBuilder = new RouteBuilder(app, new RouteHandler(RemoteUriHelper.HandlerAsync));
            routeBuilder.MapRoute("help_and_shiny", "remoteuri");
            app.UseRouter(routeBuilder.Build());

            app.UseBasicAuthentication(options => {
                options.Events = new BasicEvents { OnSignIn = securityManager.SignInAsync };
            });

            app.Use((context, next) => {
                if (!context.User.Identity.IsAuthenticated) {
                    return context.Authentication.ChallengeAsync();
                } else {
                    return next();
                }
            });

            app.UseMvc();
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:34,代码来源:Startup.cs

示例2: Configure

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();

            var routeBuilder = new RouteBuilder(app);
            //routeBuilder.MapGet("", context => context.Response.WriteAsync("Hello from Routing"));
            routeBuilder.MapGet("sub", context => context.Response.WriteAsync("Hello from sub!"));
            routeBuilder.MapGet("item/{id:int}", context => context.Response.WriteAsync($"Id: {context.GetRouteValue("id")}"));
            routeBuilder.MapGet("item/{itemName}", context => context.Response.WriteAsync($"Item: {context.GetRouteValue("itemName")}"));
            app.UseRouter(routeBuilder.Build());

            app.UseMvc();
        }
开发者ID:naeemsarfraz,项目名称:aspnet5-workshop,代码行数:14,代码来源:Startup.cs

示例3: Configure

        public void Configure(IApplicationBuilder builder)
        {
            var endpoint1 = new DelegateRouteEndpoint(async (context) =>
                                                        await context
                                                                .HttpContext
                                                                .Response
                                                                .WriteAsync(
                                                                  "match1, route values -" + context.RouteData.Values.Print()));

            var endpoint2 = new DelegateRouteEndpoint(async (context) =>
                                                        await context
                                                                .HttpContext
                                                                .Response
                                                                .WriteAsync("Hello, World!"));

            var routeBuilder = new RouteBuilder();
            routeBuilder.DefaultHandler = endpoint1;
            routeBuilder.ServiceProvider = builder.ApplicationServices;

            routeBuilder.AddPrefixRoute("api/store");

            routeBuilder.MapRoute("defaultRoute",
                                  "api/constraint/{controller}",
                                  null,
                                  new { controller = "my.*" });
            routeBuilder.MapRoute("regexStringRoute",
                                  "api/rconstraint/{controller}",
                                  new { foo = "Bar" },
                                  new { controller = new RegexRouteConstraint("^(my.*)$") });
            routeBuilder.MapRoute("regexRoute",
                                  "api/r2constraint/{controller}",
                                  new { foo = "Bar2" },
                                  new
                                  {
                                      controller = new RegexRouteConstraint(
                                          new Regex("^(my.*)$", RegexOptions.None, TimeSpan.FromSeconds(10)))
                                  });

            routeBuilder.MapRoute("parameterConstraintRoute",
                                  "api/{controller}/{*extra}",
                                  new { controller = "Store" });

            routeBuilder.AddPrefixRoute("hello/world", endpoint2);

            routeBuilder.MapLocaleRoute("en-US", "store/US/{action}", new { controller = "Store" });
            routeBuilder.MapLocaleRoute("en-GB", "store/UK/{action}", new { controller = "Store" });

            routeBuilder.AddPrefixRoute("", endpoint2);

            builder.UseRouter(routeBuilder.Build());
        }
开发者ID:TerabyteX,项目名称:Routing,代码行数:51,代码来源:Startup.cs

示例4: Configure

        // 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/>");
            });
        }
开发者ID:ChujianA,项目名称:aspnetcore-doc-cn,代码行数:52,代码来源:Startup.cs

示例5: Configure

            public void Configure(IApplicationBuilder app)
            {
                app.UseCors(policy => policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin()
                    .AllowCredentials()
                );

                var builder = new RouteBuilder(app);
                ((HttpCommandRouteMapper)app.ApplicationServices.GetService(typeof(HttpCommandRouteMapper))).Map(builder);
                ((HttpQueryRouteMapper)app.ApplicationServices.GetService(typeof(HttpQueryRouteMapper))).Map(builder);
                app.UseRouter(builder.Build());
            }
开发者ID:mhwk,项目名称:spray-chronicle,代码行数:14,代码来源:HttpServer.cs

示例6: Initialize

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="rpcConfig"></param>
        public static void Initialize(IApplicationBuilder app, RpcConfig rpcConfig)
        {
            RpcManager.Initialize(rpcConfig);

            if (rpcConfig?.Service?.Paths == null) return;
            if (app == null) return;

            var routers = new RouteBuilder(app);

            foreach (var path in rpcConfig.Service.Paths)
            {
                routers.MapRoute(path + "{*RpcLiteServicePath}", context => RpcManager.ProcessAsync(new AspNetCoreServerContext(context)));
            }
            var routes1 = routers.Build();
            app.UseRouter(routes1);
        }
开发者ID:chrishaly,项目名称:RpcLite,代码行数:21,代码来源:AspNetCoreInitializer.cs

示例7: Configure

        // 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
        }
开发者ID:ColinDabritz,项目名称:Docs,代码行数:46,代码来源:Startup.cs

示例8: Configure

        public void Configure(IApplicationBuilder app)
        {
            var endpoint1 = new RouteHandler((c) =>
            {
                return c.Response.WriteAsync($"match1, route values - {string.Join(", ", c.GetRouteData().Values)}");
            });

            var endpoint2 = new RouteHandler((c) => c.Response.WriteAsync("Hello, World!"));

            var routeBuilder = new RouteBuilder(app)
            {
                DefaultHandler = endpoint1,
            };

            routeBuilder.MapRoute("api/status/{item}", c => c.Response.WriteAsync($"{c.GetRouteValue("item")} is just fine."));
            routeBuilder.MapRoute("localized/{lang=en-US}", b =>
            {
                b.Use(next => async (c) =>
                {
                    var culture = new CultureInfo((string)c.GetRouteValue("lang"));
#if DNX451
                    Thread.CurrentThread.CurrentCulture = culture;
                    Thread.CurrentThread.CurrentUICulture = culture;
#else
                    CultureInfo.CurrentCulture = culture;
                    CultureInfo.CurrentUICulture = culture;
#endif
                    await next(c);
                });

                b.Run(c => c.Response.WriteAsync($"What would you do with {1000000m:C}?"));
            });

            routeBuilder.AddPrefixRoute("api/store", endpoint1);
            routeBuilder.AddPrefixRoute("hello/world", endpoint2);

            routeBuilder.MapLocaleRoute("en-US", "store/US/{action}", new { controller = "Store" });
            routeBuilder.MapLocaleRoute("en-GB", "store/UK/{action}", new { controller = "Store" });

            routeBuilder.AddPrefixRoute("", endpoint2);

            app.UseRouter(routeBuilder.Build());
        }
开发者ID:leloulight,项目名称:Routing,代码行数:43,代码来源:Startup.cs

示例9: Configure

        // 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/>");
            });
        }
开发者ID:Corays,项目名称:Docs,代码行数:43,代码来源:Startup.cs

示例10: Configure

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePages(subApp =>
                {
                    subApp.Run(async context =>
                    {
                        context.Response.ContentType = "text/html";
                        await context.Response.WriteAsync($"Error @ {context.Response.StatusCode}");
                    });
                });
            }

            logFactory.AddConsole(LogLevel.Trace);
            logFactory.AddSerilog();

            var logger = logFactory.CreateLogger<Startup>();

            logger.LogTrace("Trace msg");
            logger.LogDebug("Debug msg");
            logger.LogInformation("Info msg");
            logger.LogWarning("Warn msg");
            logger.LogError("Error msg");
            logger.LogCritical("Critical msg");

            app.UseMiddleware<RequestIdMiddleware>();

            //app.Run(ctx =>
            //{
            //    //throw new Exception("some error");
            //    //ctx.Response.StatusCode = 500;
            //    return Task.FromResult(0);
            //});


            //app.UseIISPlatformHandler();
            //app.UseFileServer();
            var router = new RouteBuilder(app)
                .MapGet("", async ctx => await ctx.Response.WriteAsync("Hello from routing"))
                .MapGet("sub", async ctx => await ctx.Response.WriteAsync("Hello from sub"))
                .MapGet("item/{id:int}", ctx => ctx.Response.WriteAsync($"Item ID: {ctx.GetRouteValue("id")}"))
                ;
            
            app.UseRouter(router.Build());
            app.UseMvc();

       
            //app.UseRequestCulture();
            //app.Run(async ctx => await ctx.Response.WriteAsync($"Hello {CultureInfo.CurrentCulture.DisplayName}"));
            //app.Run(async ctx => await ctx.Response.WriteAsync($"{Configuration["greeting"]}"));
        }
开发者ID:eaardal,项目名称:aspnet5-workshop,代码行数:56,代码来源:Startup.cs


注:本文中的IApplicationBuilder.UseRouter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。