如何组织.NET 6 Minimal Web Api路由 将自定义路由移出Program.cs
.NET 6 Minimal API 拆分路由到独立类的实现方案
你已经编写的EmployeeApi路由定义类符合官方规范,不需要额外的全局自动注册配置,只需要手动调用映射方法即可生效,具体操作如下:
具体操作步骤
- 第一步:如果
EmployeeApi类在单独的命名空间下,先在Program.cs顶部引入对应命名空间,同项目同命名空间下可跳过此步骤。 - 第二步:在Program.cs中
app.Build()完成后、app.Run()执行前,调用EmployeeApi类的静态MapRoutes方法即可。
注意:路由映射需要放在认证、授权中间件之后,否则接口的权限校验会失效。另外你当前代码中
UseAuthorization和UseAuthentication的顺序写反了,需要调整为先调用认证再调用授权,否则授权逻辑不会生效。
修改后的Program.cs代码如下:
var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("AppDb"); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString)); builder.Services.AddAuthorization(); builder.Services.AddAuthentication(); var app = builder.Build(); // Configure the HTTP request pipeline. if (builder.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); // 调整中间件顺序:先认证,再授权 app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Hello World!"); // 注册Employee相关路由 EmployeeApi.MapRoutes(app); app.Run();
进阶优化:批量注册路由类
如果项目中存在多个类似EmployeeApi的路由定义类,你可以通过反射实现批量注册,无需逐个手动调用:
- 首先定义一个接口用于标记路由类:
public interface IApiEndpoint { static abstract void MapRoutes(IEndpointRouteBuilder routes); }
- 让所有路由类实现该接口:
public class EmployeeApi : IApiEndpoint { public static void MapRoutes(IEndpointRouteBuilder routes) { // 原有路由逻辑不变 routes.MapGet("/api/employees", async ([FromServices] AppDbContext db) => { return await db.Employees.ToListAsync(); }); routes.MapGet("api/employees/{id}", async (int id, [FromServices] AppDbContext db) => { return await db.Employees.FindAsync(id); }); } }
- 编写扩展方法实现批量扫描注册:
public static class EndpointRouteBuilderExtensions { public static void MapAllEndpoints(this IEndpointRouteBuilder routes) { var endpointTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(t => t.IsAssignableTo(typeof(IApiEndpoint)) && !t.IsAbstract && !t.IsInterface); foreach (var type in endpointTypes) { var mapMethod = type.GetMethod(nameof(IApiEndpoint.MapRoutes), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); mapMethod?.Invoke(null, new object[] { routes }); } } }
- 在Program.cs中替换单个调用,改为批量注册:
// 替换原来的EmployeeApi.MapRoutes(app); app.MapAllEndpoints();
内容的提问来源于stack exchange,提问作者Chad Lomax
相关产品推荐
相关产品推荐

