public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHangfireServer(); app.UseHangfireDashboard(); //方式一 //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); //方式二 //var endpoint = new RouteHandler((c) => c.Response.WriteAsync("Hello, I am Routing!")); //app.UseRouter(endpoint); //方式三 var endpoint = new RouteHandler((c) =>c.Response.WriteAsync($"Hello, I am Routing! your item is {c.GetRouteValue("item")}")); var resolver = app.ApplicationServices.GetRequiredService(); var runRoute = new Route(endpoint, "{item=home}", resolver); app.UseRouter(runRoute); //方式四 var runRoute1 = new Route(endpoint, "{item=home}", resolver); var otherRoute = new Route(endpoint, "other/{item=other_home}", resolver); var routeCollection = new RouteCollection(); routeCollection.Add(runRoute1); routeCollection.Add(otherRoute); app.UseRouter(routeCollection); //方式五 var routeBuilder = new RouteBuilder(app) { DefaultHandler = endpoint, }; routeBuilder.MapRoute("default", "{item=home}"); routeBuilder.MapRoute("other", "other/{item=other_home}"); app.UseRouter(routeBuilder.Build()); //方式六,改写handler var myendpoint = new MyRouteHandler(); var myrouteBuilder = new RouteBuilder(app) { DefaultHandler = myendpoint, }; myrouteBuilder.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); app.UseRouter(myrouteBuilder.Build()); }
自定义hanlder
public class MyRouteHandler : IRouter { public VirtualPathData GetVirtualPath(VirtualPathContext context) { return null; } public Task RouteAsync(RouteContext context) { context.Handler = (c) => { var printStr = $"controller:{c.GetRouteValue("controller")}," + $"action:{c.GetRouteValue("action")},id:{c.GetRouteValue("id")}"; return c.Response.WriteAsync(printStr); }; return Microsoft.AspNetCore.Routing.Internal.TaskCache.CompletedTask; } }