如何用Swashbuckle.AspNetCore通过XML注释为IList类型设置Swagger请求示例
解决方案
方案1:修正XML注释的示例格式
Swashbuckle 解析XML注释的example节点时要求数组使用标准JSON格式,原写法使用单引号不符合JSON规范,改为双引号包裹的标准数组格式即可:
/// <summary> /// Gets or sets the list of Toys. /// </summary> /// <example>["Tiger", "Lion", "Doll"]</example> [JsonProperty(PropertyName = "toys", Required = Required.Always)] [Required] public IList<string> Toys { get; set; }
注意:使用该方案前需确认项目已开启XML文档生成,且Swagger配置中已添加IncludeXmlComments配置读取XML注释文件。
方案2:使用Swagger特性直接指定示例
如果方案1不生效(常见于低版本Swashbuckle),可以安装Swashbuckle.AspNetCore.Annotations NuGet包,通过特性直接指定示例:
/// <summary> /// Gets or sets the list of Toys. /// </summary> [JsonProperty(PropertyName = "toys", Required = Required.Always)] [Required] [SwaggerSchemaExample(new string[] { "Tiger", "Lion", "Doll" })] public IList<string> Toys { get; set; }
注册Swagger时需要开启注解支持:
builder.Services.AddSwaggerGen(options => { options.EnableAnnotations(); // 其余原有配置 });
方案3:自定义SchemaFilter全局处理
如果需要批量处理所有集合类型的示例,可以实现自定义Schema过滤器:
- 定义过滤器类
public class CollectionExampleSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 处理IList<string>类型的属性 if (context.Type == typeof(IList<string>)) { schema.Example = new OpenApiArray { new OpenApiString("Tiger"), new OpenApiString("Lion") }; } // 可扩展其他集合类型的处理逻辑 } }
- 注册过滤器
builder.Services.AddSwaggerGen(options => { options.SchemaFilter<CollectionExampleSchemaFilter>(); // 其余原有配置 });
内容的提问来源于stack exchange,提问作者Gohawks
相关产品推荐
相关产品推荐

