//builder.MapRoute("default1", "{controller}/{action}/{id?}", new { controller = "Home", action = "index" }); //builder.MapRoute("default2", "{controller=home}/{action=index}/{id?}", defaults:null); //builder.MapRoute("default3", "{controller=home}/{action=index}/{*id?}", defaults:null);//id/a/b/c全部匹配 //builder.MapRoute("default4", "{controller=home}/{action=index}/{*id:regex(^\d{{2,3}}$)}", defaults: null);//正则表达式匹配2到3位的数字 //builder.MapRoute("default5", // "{controller}/{action}/{id?}", // null, // constraints: new { action = "index|index2" // , id = new IdScopeConstraint() } // ); builder.MapRoute("default6", "{controller}/{action}/{id?}", null, constraints: new { action = "index|index2", id = new RangeRouteConstraint(10, 20) // Microsoft.AspNetCore.Routing.Constraints.* 查找其他的内置 } );
RouteHandler customRouteHandler = new RouteHandler(async context => { await context.Response.WriteAsync("custom routeHandler"); }); RouteBuilder routeBuilder = new RouteBuilder(app, customRouteHandler); ////参考文章:https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-3_4-routing.html //http://localhost:5000/home/test/3、http://localhost:5000/home/route/3 默认customRouteHandler routeBuilder.MapRoute("default route", "Home/{operation:regex(^route|test$)}/{id:int}"); //http://localhost:5000/home/route1 routeBuilder.MapRoute("Home/router1", async context => { await context.Response.WriteAsync("router1 handler"); }); //http://localhost:5000/home/router2 routeBuilder.MapRoute("Home/router2", async context => { await context.Response.WriteAsync("router2 handler"); }); routeBuilder.MapRoute("files/{filename}.{ext:regex(^jpg|rar$)}", async context => { await context.Response.WriteAsync("router3 handler,file:" + context.GetRouteValue("filename") + "." + context.GetRouteValue("ext")); }); routeBuilder.MapRoute("download/{f}.{e:regex(^xls$)}", async context => { await context.Response.WriteAsync("router4 handler,file:" + context.GetRouteValue("f") + "." + context.GetRouteValue("e")); }); routeBuilder.MapRoute("download2/{filename}.{ext:regex(^xls$)}", context => { RouteValueDictionary routeDataMap = new RouteValueDictionary { { "filename",DateTime.Now.ToLongTimeString()}, { "ext","ecl"}, }; var vpc = new VirtualPathContext(context, null, routeDataMap); var path = routeBuilder.Build().GetVirtualPath(vpc).VirtualPath; return context.Response.WriteAsync("router5 handler,file:" + path); }); app.UseRouter(routeBuilder.Build()); app.Run(async context => await context.Response.WriteAsync("hello world"));