.NET 6 Web API如何为所有Swagger请求添加固定查询参数?
在.NET 6 Web API中让Swagger自动携带必填上下文查询参数
可以通过自定义Swagger操作过滤器实现这个需求,以下是两种实用方案:
方案一:全局为受保护端点添加参数
如果所有受指定AuthPolicy保护的端点都需要携带clientId这类参数,可创建全局操作过滤器自动注入:
1. 编写操作过滤器
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Mvc.Authorization; public class RequiredContextQueryFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 检查当前端点是否受目标AuthPolicy保护 var requiresAuthPolicy = context.ApiDescription.ActionDescriptor.EndpointMetadata .Any(m => m is AuthorizeAttribute authAttr && authAttr.Policy == "YourAuthPolicyName"); if (requiresAuthPolicy) { // 避免重复添加参数 if (!operation.Parameters.Any(p => p.Name.Equals("clientId", StringComparison.OrdinalIgnoreCase))) { operation.Parameters.Add(new OpenApiParameter { Name = "clientId", In = ParameterLocation.Query, Required = true, Schema = new OpenApiSchema { Type = "integer" }, // 设置默认值,Swagger调试时会自动填充 Example = new OpenApiInteger(1) }); } } } }
2. 注册过滤器到Swagger
在Program.cs的Swagger配置中添加该过滤器:
builder.Services.AddSwaggerGen(c => { // 注册自定义操作过滤器 c.OperationFilter<RequiredContextQueryFilter>(); // 其他Swagger配置(如文档标题、版本等) });
方案二:针对特定端点添加参数
如果仅部分端点需要携带上下文参数,可通过自定义特性标记目标端点,再用过滤器识别并添加参数:
1. 创建自定义特性
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class RequireQueryParameterAttribute : Attribute { public string Name { get; } public string Type { get; } public RequireQueryParameterAttribute(string name, string type) { Name = name; Type = type; } }
2. 标记目标端点
在控制器方法上添加特性:
[HttpPost("SaveClient")] [Authorize(Policy = "YourAuthPolicyName")] [RequireQueryParameter("clientId", "integer")] public IActionResult SaveClient([FromBody] ClientDto clientData) { // 业务逻辑实现 return Ok(); }
3. 修改操作过滤器
public class RequiredContextQueryFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var requireParams = context.ApiDescription.ActionDescriptor.EndpointMetadata .OfType<RequireQueryParameterAttribute>(); foreach (var param in requireParams) { if (!operation.Parameters.Any(p => p.Name.Equals(param.Name, StringComparison.OrdinalIgnoreCase))) { var schema = param.Type switch { "integer" => new OpenApiSchema { Type = "integer" }, "string" => new OpenApiSchema { Type = "string" }, _ => new OpenApiSchema { Type = "string" } }; operation.Parameters.Add(new OpenApiParameter { Name = param.Name, In = ParameterLocation.Query, Required = true, Schema = schema, Example = param.Type == "integer" ? new OpenApiInteger(1) : new OpenApiString("default_value") }); } } } }
效果说明
配置完成后,Swagger文档中符合条件的端点会自动显示必填的查询参数,点击「Try it out」时参数会自动填充默认值,用户可根据实际情况修改,确保请求符合AuthPolicy的要求。
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

