如何配置AddSwaggerGen将未被Controller使用的DTO加入swagger.json
问题:如何将未在Controller中使用的DTO加入Swagger文档?
我使用services.AddSwaggerGen()生成swagger.json,当前配置代码如下:
services.AddSwaggerGen(c => { c.CustomOperationIds(apiDesc => { if (apiDesc.TryGetMethodInfo(out var methodInfo)) { if (methodInfo.GetCustomAttributes(typeof(HttpMethodAttribute)).FirstOrDefault() is HttpMethodAttribute attr) { if (!string.IsNullOrEmpty(attr.Template)) { return attr.Template; } } } return $"{apiDesc.HttpMethod.Substring(0, 1)}{apiDesc.HttpMethod.Substring(1, apiDesc.HttpMethod.Length -1).ToLower()}"; }); c.SwaggerDoc("v1", new OpenApiInfo() { Title = "Time API", Version = "v1" }); });
当前配置运行正常,但存在一个未在Controller中显式使用的DTO未被添加到swagger.json中,请问是否可以通过配置让该DTO也被包含进swagger.json?
解决方案
方法一:手动指定单个DTO类型
通过自定义SchemaFilter强制将目标DTO加入Swagger Schema:
- 定义Schema过滤器类:
public class IncludeUnreferencedDtoFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 替换为你需要包含的DTO类型 var targetDtoType = typeof(YourUnreferencedDto); // 检查类型是否已加入Schema,未加入则生成并添加 if (!context.SchemaRepository.TryLookupByType(targetDtoType, out _)) { context.SchemaGenerator.GenerateSchema(targetDtoType, context.SchemaRepository); } } }
- 在Swagger配置中注册过滤器:
services.AddSwaggerGen(c => { // 保留原有配置代码 c.CustomOperationIds(...); c.SwaggerDoc("v1", ...); // 添加过滤器 c.SchemaFilter<IncludeUnreferencedDtoFilter>(); });
方法二:批量包含指定范围的DTO
如果需要一次性加入某个程序集/命名空间下的所有DTO,可通过DocumentFilter实现批量扫描添加:
- 定义文档过滤器类:
public class IncludeAllDtosDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { // 通过任意一个DTO类型获取目标程序集 var dtoAssembly = typeof(YourUnreferencedDto).Assembly; // 筛选目标命名空间下的非抽象、非泛型DTO类型 var dtoTypes = dtoAssembly.GetTypes() .Where(t => t.Namespace == "YourProject.Dtos.Namespace" && !t.IsAbstract && !t.IsGenericTypeDefinition); foreach (var type in dtoTypes) { if (!context.SchemaRepository.TryLookupByType(type, out _)) { var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository); swaggerDoc.Components.Schemas.TryAdd(type.Name, schema); } } } }
- 在Swagger配置中注册该过滤器:
services.AddSwaggerGen(c => { // 保留原有配置代码 c.CustomOperationIds(...); c.SwaggerDoc("v1", ...); // 添加文档过滤器 c.DocumentFilter<IncludeAllDtosDocumentFilter>(); });
注意事项
- 目标DTO的访问修饰符必须为
public,否则Swagger无法生成对应的Schema结构。 - 如果需要给DTO添加注释说明,需开启项目的“生成XML文档文件”功能,并在Swagger配置中通过
c.IncludeXmlComments()引入生成的XML文件。
内容的提问来源于stack exchange,提问作者BennoDual
相关产品推荐
相关产品推荐

