在.NET 8.0中用Swashbuckle ISchemaFilter为属性添加Swagger样式化描述
解决Swagger UI属性自定义带样式描述的问题
当前你的CustomSchemaFilter仅能处理类/接口级别的SchemaDescriptionAttribute,无法识别属性上的注解。以下是修改后的实现方案,支持属性级自定义描述并兼容CSS样式渲染:
修改CustomSchemaFilter实现
更新ISchemaFilter的实现,新增属性遍历逻辑,读取每个属性上的自定义特性并赋值给对应Schema的描述:
public class CustomSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 处理类/接口级别的全局描述 var typeAttr = context.Type.GetCustomAttributes(typeof(SchemaDescriptionAttribute), true) .FirstOrDefault() as SchemaDescriptionAttribute; if (typeAttr != null) { schema.Description = typeAttr.Description; } // 遍历所有公开实例属性,处理属性级描述 var properties = context.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { var propAttr = prop.GetCustomAttributes(typeof(SchemaDescriptionAttribute), true) .FirstOrDefault() as SchemaDescriptionAttribute; // 找到对应Schema属性并更新描述 if (propAttr != null && schema.Properties.TryGetValue(prop.Name, out var propSchema)) { propSchema.Description = propAttr.Description; } } } }
支持CSS样式渲染
Swagger UI允许在描述中嵌入HTML代码,直接在SchemaDescriptionAttribute的内容中添加CSS样式即可:
[SchemaDescription("only works on type declaration")] public interface IExample { [SchemaDescription("<span style='color: #27ae60; font-weight: 600;'>user_id (integer, required):</span> The unique identifier for the user. <span style='color: #e74c3c;'>Zero is not a valid user ID, must be non-zero.</span>")] public int id { get; set; } }
确保Swagger配置支持HTML渲染
在Swagger服务配置中,确保没有禁用HTML解析(默认情况下Swashbuckle会允许HTML渲染,若有特殊配置需调整):
services.AddSwaggerGen(c => { c.SchemaFilter<CustomSchemaFilter>(); // 其他Swagger配置... });
说明
- 上述代码兼容类、接口的属性处理,
Type.GetProperties()会正确获取接口的公开实例属性 - 描述中的HTML/CSS会被Swagger UI直接渲染,可根据需求调整样式(如颜色、字体粗细、换行等)
- 若属性名称在Schema中是驼峰命名(如
id变为userId),需确保schema.Properties.TryGetValue的键与实际Schema属性名一致,可通过配置c.DescribeAllParametersInCamelCase()统一处理命名规则
内容的提问来源于stack exchange,提问作者user30909924
相关产品推荐
相关产品推荐

