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

ASP.NET Core:如何在Swagger UI中忽略复杂类型的模型绑定属性

问题描述

需要将ASP.NET Core控制器方法的多个参数合并到一个类中,其中部分通过自定义模型绑定从HttpContext获取的环境参数需在Swagger UI中隐藏。当前API在Postman中调用正常,但尝试自定义[SwaggerIgnore]特性、[SwaggerSchema(ReadOnly = true)]等方案均无法隐藏指定属性,且不想使用[JsonIgnore](属于序列化关注点,与API文档需求分离)。

使用版本:

  • Swashbuckle.AspNetCore 6.5.0
  • Swashbuckle.AspNetCore.Annotations 6.5.0
  • .NET 7 / ASP.NET Core

测试代码:

[HttpPost]
public ActionResult Post(TestDetails testDetails)
{
    return Ok();
}

public record TestDetails
{
    [FromBody]
    public Body? body { get; init; }

    [SwaggerIgnore]
    public string? ignoreMe { get; init; }

    [SwaggerIgnore, ModelBinder(typeof(EnvironmentBinder))]
    public IPAddress? ipAddress { get; init; }

    [SwaggerIgnore, ModelBinder(typeof(DefaultValueBinder))]
    public string? Default { get; init; }

    [FromHeader(Name = "Accept-Language")]
    public string? preferredLanguages { get; init; }

    [FromQuery]
    public string? selectedLanguage { get; init; }
}

public record Body
{
    public string? name { get; init; }

    public string? stageName { get; init; }
}
解决方案

通过自定义SchemaFilter识别[SwaggerIgnore]特性,从Swagger的模型定义中移除指定属性,步骤如下:

  1. 定义SwaggerIgnore特性
[AttributeUsage(AttributeTargets.Property)]
public class SwaggerIgnoreAttribute : Attribute
{
}
  1. 实现ISchemaFilter过滤器
    该过滤器会扫描模型属性,移除带有[SwaggerIgnore]特性的属性:
public class SwaggerIgnoreFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null) return;

        // 获取所有标记了SwaggerIgnore的属性名(转小写避免大小写问题)
        var ignoreProps = context.Type.GetProperties()
            .Where(p => Attribute.IsDefined(p, typeof(SwaggerIgnoreAttribute)))
            .Select(p => p.Name.ToLowerInvariant())
            .ToList();

        // 遍历并移除Swagger模型中的对应属性
        foreach (var prop in schema.Properties.ToList())
        {
            if (ignoreProps.Contains(prop.Key.ToLowerInvariant()))
            {
                schema.Properties.Remove(prop.Key);
            }
        }
    }
}
  1. 注册过滤器到Swagger配置
    在Program.cs的Swagger注册代码中添加该过滤器:
builder.Services.AddSwaggerGen(c =>
{
    // 注册自定义过滤器
    c.SchemaFilter<SwaggerIgnoreFilter>();
    
    // 其他Swagger配置(如文档标题、版本等)
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
});
  1. 验证效果
    启动项目后,Swagger UI将不再显示标记了[SwaggerIgnore]的属性,同时不影响模型绑定和API的正常调用。

注意:如果标记了[SwaggerIgnore]的属性被Swashbuckle解析为顶级请求参数(如Header/Query参数),需额外实现IOperationFilter来移除这些参数。但当前代码结构下(参数合并到类中),仅需SchemaFilter即可生效。

内容的提问来源于stack exchange,提问作者M. Koch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:45:25