如何创建自定义Swagger文档属性类以简化API注解代码?
合并Swagger注解为自定义属性的可行方案
你想把多个Swagger相关注解整合到一个自定义属性里减少重复代码的思路是可行的,但你当前设想的自定义属性写法不符合C#语法规范——属性的构造函数里不能直接嵌套其他属性。正确的实现方式需要结合自定义属性和Swagger操作过滤器来完成,具体步骤如下:
原API代码示例
[HttpGet] [SwaggerOperation( Summary = "Get the list of customers", Description = "This Api returns the list of customers from database and display on Customer Screen", Tags = ["Customer"] ) ] [SwaggerResponse(200, description: "Returns a list of customers if the request was successful.")] [SwaggerResponse(500, "Internal Server Error along with the complete Error message.")] public async Task<ActionResult> GetCustomersAsync(CancellationToken cancellationToken) { // Code to Get the customers return Ok(customers); }
正确实现步骤
1. 定义自定义属性类
这个类只负责存储需要的配置参数,不直接添加Swagger注解:
[AttributeUsage(AttributeTargets.Method, Inherited = true)] public class SwaggerDocumentationAttribute : Attribute { public string OperationSummary { get; } public string OperationDescription { get; } public string[] OperationTags { get; } public string ResponseSuccessMessage { get; } public SwaggerDocumentationAttribute( string operationSummary, string operationDescription, string[] operationTags, string responseSuccessMessage) { OperationSummary = operationSummary; OperationDescription = operationDescription; OperationTags = operationTags; ResponseSuccessMessage = responseSuccessMessage; } }
2. 实现Swagger操作过滤器
通过IOperationFilter接口,在Swagger生成文档时读取自定义属性的参数,动态注入Swagger配置:
public class SwaggerDocumentationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 获取方法上的自定义属性 var docAttr = context.MethodInfo.GetCustomAttribute<SwaggerDocumentationAttribute>(); if (docAttr == null) return; // 设置接口的摘要、描述和标签 operation.Summary = docAttr.OperationSummary; operation.Description = docAttr.OperationDescription; operation.Tags = docAttr.OperationTags.Select(tag => new OpenApiTag { Name = tag }).ToList(); // 添加200成功响应 operation.Responses["200"] = new OpenApiResponse { Description = $"Returns a {docAttr.ResponseSuccessMessage} if the request was successful." }; // 添加500错误响应 operation.Responses["500"] = new OpenApiResponse { Description = "Internal Server Error along with the complete Error message." }; } }
3. 注册Swagger过滤器
在项目的Program.cs(或Startup.cs)中,将过滤器注册到Swagger服务:
builder.Services.AddSwaggerGen(c => { // 注册自定义过滤器 c.OperationFilter<SwaggerDocumentationFilter>(); });
4. 使用自定义属性
现在可以在API方法上直接使用自定义属性,替代多个Swagger注解:
[HttpGet] [SwaggerDocumentation( "Get the list of customers", "This Api returns the list of customers from database and display on Customer Screen", new[] { "Customer" }, "list of customers" )] public async Task<ActionResult> GetCustomersAsync(CancellationToken cancellationToken) { // 业务逻辑代码 return Ok(customers); }
方案说明
这个方案完全可行,既达到了减少重复注解的目的,又符合C#语法规范。后续如果需要扩展(比如添加其他响应码、参数校验说明等),只需修改自定义属性和过滤器即可,扩展性很强。
内容的提问来源于stack exchange,提问作者Pankaj
相关产品推荐
相关产品推荐

