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

.NET Swagger如何从示例值中排除指定属性?

如何从Swagger示例值中排除指定属性?

在.NET项目中使用Swagger时,若希望示例值仅保留带有<example>标签的属性,可通过以下两种方式实现:

方法1:自定义SchemaFilter(推荐)

通过实现ISchemaFilter接口,在Swagger生成Schema时自动移除未设置示例值的属性。

步骤1:创建自定义过滤器类

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class ExcludeUnspecifiedExamplePropertiesFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null) return;

        // 筛选出所有未设置Example的属性
        var propertiesToRemove = schema.Properties
            .Where(pair => pair.Value.Example == null)
            .Select(pair => pair.Key)
            .ToList();

        // 从Schema中移除这些属性
        foreach (var propertyName in propertiesToRemove)
        {
            schema.Properties.Remove(propertyName);
        }
    }
}

步骤2:注册过滤器到Swagger配置

修改AddSwaggerGen的配置代码,添加自定义过滤器:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", openApiInfo);
    c.AddSecurityDefinition("Bearer", openApiSecurityScheme);
    c.AddSecurityRequirement(openApiSecurityRequirement);

    // 设置XML注释路径
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);

    // 注册自定义过滤器
    c.SchemaFilter<ExcludeUnspecifiedExamplePropertiesFilter>();
});

方法2:通过XML注释设置空示例(局限)

若仅需临时处理单个属性,可给不需要显示的属性添加空的<example>标签:

public class CreateRequest
{
    /// <summary>
    /// ID of the user if available
    /// </summary>
    /// <example></example>
    public string ID { get; set; }

    /// <summary>
    /// ExampleSetValue
    /// </summary>
    /// <example>Example Value</example>
    public string ExampleSetValue { get; set; }
}

注意:此方法会让属性在示例中显示为"ID": "",而非完全移除,仅适用于允许空值展示的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:01:17