ASP.NET Core Web API:使用自定义模型绑定器时配置Swashbuckle
解决Swashbuckle无法识别自定义模型绑定复杂类型参数来源的问题
针对你用自定义模型绑定器封装RequestAttributes后,Swagger文档将其识别为Body参数的问题,可通过自定义Swagger过滤器手动映射参数来源,具体步骤如下:
1. 给RequestAttributes属性标记绑定来源注解
确保RequestAttributes类的每个属性都标注对应的绑定来源注解,示例:
public class RequestAttributes { [FromHeader(Name = "X-User-Id")] [Required] public string UserId { get; set; } [FromQuery(Name = "page")] public int PageNumber { get; set; } [FromQuery(Name = "pageSize")] public int PageSize { get; set; } }
2. 实现自定义IOperationFilter
这个过滤器会找到控制器方法中类型为RequestAttributes的参数,将其内部属性拆分为对应来源的Swagger参数,并移除默认生成的Body参数:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Reflection; public class RequestAttributesOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 筛选出所有类型为RequestAttributes的参数描述 var targetParams = context.ApiDescription.ParameterDescriptions .Where(p => p.ParameterType == typeof(RequestAttributes)) .ToList(); if (!targetParams.Any()) return; // 移除Swagger默认生成的Body参数 operation.RequestBody = null; foreach (var paramDesc in targetParams) { // 遍历RequestAttributes的所有属性 foreach (var prop in typeof(RequestAttributes).GetProperties()) { // 根据注解判断参数来源 var headerAttr = prop.GetCustomAttribute<FromHeaderAttribute>(); var queryAttr = prop.GetCustomAttribute<FromQueryAttribute>(); OpenApiParameter swaggerParam = null; if (headerAttr != null) { swaggerParam = new OpenApiParameter { Name = headerAttr.Name ?? prop.Name, In = ParameterLocation.Header, Required = prop.GetCustomAttribute<RequiredAttribute>() != null, Schema = context.SchemaGenerator.GenerateSchema(prop.PropertyType, context.SchemaRepository) }; } else if (queryAttr != null) { swaggerParam = new OpenApiParameter { Name = queryAttr.Name ?? prop.Name, In = ParameterLocation.Query, Required = prop.GetCustomAttribute<RequiredAttribute>() != null, Schema = context.SchemaGenerator.GenerateSchema(prop.PropertyType, context.SchemaRepository) }; } if (swaggerParam != null) { operation.Parameters.Add(swaggerParam); } } } } }
3. 在Startup.cs中注册过滤器
在ConfigureServices方法的AddSwaggerGen配置中添加自定义过滤器:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API名称", Version = "v1" }); // 注册自定义操作过滤器 c.OperationFilter<RequestAttributesOperationFilter>(); });
原理说明
Swashbuckle默认只会解析控制器方法直接参数上的[FromXxx]注解,对于通过自定义模型绑定器绑定的复杂类型,不会自动遍历内部属性的绑定配置。通过自定义IOperationFilter,我们可以手动解析复杂类型的属性注解,生成对应位置的Swagger参数,同时移除默认的Body参数,让文档正确展示参数来源。
内容的提问来源于stack exchange,提问作者M. Koch
相关产品推荐
相关产品推荐

