You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让.NET Core的Swashbuckle识别Description属性生成Swagger参数描述

实现方案

Swashbuckle 有对应的扩展点可以实现这个需求,不需要重复标注两个特性,下面提供两种可行方案:

方案1:内置配置开启(适配 Swashbuckle.AspNetCore 6.x 及以上版本)

最新版 Swashbuckle 已经内置了对 System.ComponentModel.Description 特性的识别支持,只需要在服务注册时开启对应配置即可:

var builder = WebApplication.CreateBuilder(args);

// 其他服务注册逻辑...

builder.Services.AddSwaggerGen(options =>
{
    // 启用注解特性解析,支持读取Description等系统特性
    options.EnableAnnotations();
    // 其余你原有的Swagger配置保留即可
});

方案2:自定义 Schema 过滤器(全版本兼容,灵活度更高)

如果内置配置不满足你的场景,可以通过自定义 ISchemaFilter 实现特性读取:

  1. 先实现过滤器类:
using System.ComponentModel;
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class DescriptionReadSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 读取属性上的Description特性
        if (context.MemberInfo != null)
        {
            var descAttribute = context.MemberInfo.GetCustomAttribute<DescriptionAttribute>();
            if (descAttribute != null)
            {
                schema.Description = descAttribute.Description;
            }
        }
        
        // 可选:如果需要读取DTO类本身的Description特性,保留下面的代码
        if (context.Type != null)
        {
            var classDescAttribute = context.Type.GetCustomAttribute<DescriptionAttribute>();
            if (classDescAttribute != null)
            {
                schema.Description = classDescAttribute.Description;
            }
        }
    }
}
  1. 在 Swagger 配置中注册过滤器:
builder.Services.AddSwaggerGen(options =>
{
    options.SchemaFilter<DescriptionReadSchemaFilter>();
    // 其余你原有的Swagger配置保留即可
});

配置完成后,只需要保留属性上的 [Description] 特性即可,Swagger 文档会自动填充对应描述内容。

内容的提问来源于stack exchange,提问作者lordkain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:15:03