如何在Minimal API中为一组端点批量应用RequireAuthorization特性
统一配置Minimal API端点授权的实现方案
方案1:封装扩展方法批量绑定授权
针对需要授权的端点集合,封装一个扩展方法一次性添加授权规则,不需要授权的端点单独配置即可。
实现代码
// 自定义扩展方法类 public static class ProductEndpointExtensions { public static IEndpointConventionBuilder MapProductEndpointsWithAuthorization( this IEndpointRouteBuilder endpoints) { return endpoints.MapCreateProductsEndpoint() .MapDebitProductStockEndpoint() .MapReplenishProductStockEndpoint() .MapGetProductByIdEndpoint() .MapGetProductsViewEndpoint() .RequireAuthorization(); } }
在Program.cs中调用:
app.UseEndpoints(endpoints => { // 批量配置需要授权的产品端点 endpoints.MapProductEndpointsWithAuthorization(); // 不需要授权的端点直接单独注册 endpoints.MapGet("/public/health", () => Results.Ok("Healthy")) .WithTags("Public"); });
方案2:按标签/前缀通过端点元数据批量配置
如果你的产品端点有统一标签(比如ProductsConfigs.Tag)或路由前缀,可以遍历端点元数据批量添加授权规则。
实现代码
app.UseEndpoints(endpoints => { // 先注册所有端点 endpoints.MapCreateProductsEndpoint() .MapDebitProductStockEndpoint() .MapReplenishProductStockEndpoint() .MapGetProductByIdEndpoint() .MapGetProductsViewEndpoint(); // 注册不需要授权的公开端点 endpoints.MapGet("/public/health", () => Results.Ok("Healthy")) .WithTags("Public"); // 给带有指定标签的端点批量添加授权 foreach (var endpoint in endpoints.DataSources.SelectMany(s => s.Endpoints) .OfType<RouteEndpoint>()) { if (endpoint.Metadata.OfType<ITagMetadata>().Any(t => t.Tags.Contains(ProductsConfigs.Tag))) { endpoint.Metadata.Add(new AuthorizeAttribute()); } } });
方案3:用路由组统一绑定授权规则
如果产品相关端点有统一的路由前缀,使用路由组批量应用授权,同时支持单独覆盖部分端点的授权规则。
实现代码
app.UseEndpoints(endpoints => { // 创建带授权的产品路由组 var productRouteGroup = endpoints.MapGroup(ProductsConfigs.ProductsPrefixUri) .RequireAuthorization() .WithTags(ProductsConfigs.Tag); // 在组内注册所有产品端点,自动继承授权规则 productRouteGroup.MapCreateProductsEndpoint() .MapDebitProductStockEndpoint() .MapReplenishProductStockEndpoint() .MapGetProductByIdEndpoint() .MapGetProductsViewEndpoint(); // 若某产品端点不需要授权,单独调用AllowAnonymous覆盖 productRouteGroup.MapGetProductsViewEndpoint() .AllowAnonymous(); // 不需要授权的端点直接在组外注册 endpoints.MapGet("/public/health", () => Results.Ok("Healthy")) .WithTags("Public"); });
内容的提问来源于stack exchange,提问作者Sameer Ahmed S
相关产品推荐
相关产品推荐

