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

在ASP.Net Core 3.1中如何让Swagger忽略嵌套模型仅展示首层属性?

实现方案(ASP.NET Core 3.1 + Swashbuckle 环境)

下面提供3种不同场景的实现方式,可根据你的需求选择:


方案1:单个属性精准忽略(仅影响Swagger文档,不改变接口序列化逻辑)

适合只有少量模型需要忽略嵌套属性的场景,不会影响接口实际返回的内容:

  1. 首先安装Swashbuckle注解包(已安装可跳过)
Install-Package Swashbuckle.AspNetCore.Annotations
  1. 在Startup.cs的ConfigureServices方法中,开启Swagger注解支持
services.AddSwaggerGen(c =>
{
    // 你的其他Swagger配置
    c.EnableAnnotations(); // 新增这行
});
  1. 在需要忽略的导航属性上标记[SwaggerIgnore]特性即可
    修改后的UserVM示例:
public class UserVM
{
    public int Id { get; set; }
    public Guid Guid { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Token { get; set; }
    public string Avatar { get; set; }
    public int IsActive { get; set; }
    public int JobTitleId { get; set; }

    [SwaggerIgnore]
    public JobTitleVM JobTitle { get; set; }

    public int UserStatusId { get; set; }

    [SwaggerIgnore]
    public UserStatusVM UserStatus { get; set; }
    
    [SwaggerIgnore]
    public virtual ICollection<UserStepsVM> UserSteps { get; set; } = new List<UserStepsVM>();
}

方案2:全局自动过滤嵌套属性(适合多模型批量处理)

如果你项目中所有模型都需要仅展示首层基础属性,自动忽略自定义复杂类型、集合类型的属性,可以自定义Schema过滤器实现全局生效:

  1. 新增自定义过滤器类,编译报错可补充引用using Microsoft.OpenApi.Models;命名空间
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Models;

public class IgnoreNestedPropertiesFilter : ISchemaFilter
{
    // 定义需要保留的基础类型列表
    private static readonly Type[] AllowBaseTypes = new[] {
        typeof(int), typeof(uint), typeof(long), typeof(ulong),
        typeof(short), typeof(ushort), typeof(byte), typeof(sbyte),
        typeof(bool), typeof(string), typeof(Guid), typeof(DateTime),
        typeof(DateTimeOffset), typeof(decimal), typeof(float), typeof(double)
    };

    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties == null) return;

        // 遍历所有属性,移除不是基础类型、以及集合类型的属性
        var ignoreProperties = context.Type.GetProperties()
            .Where(p => !AllowBaseTypes.Contains(p.PropertyType) 
                        || typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(string))
            .Select(p => char.ToLowerInvariant(p.Name[0]) + p.Name.Substring(1)) // 适配驼峰命名规则
            .ToList();

        foreach (var propName in ignoreProperties)
        {
            if (schema.Properties.ContainsKey(propName))
            {
                schema.Properties.Remove(propName);
            }
        }
    }
}
  1. 在Startup.cs的AddSwaggerGen配置中注册过滤器
services.AddSwaggerGen(c =>
{
    // 你的其他Swagger配置
    c.SchemaFilter<IgnoreNestedPropertiesFilter>(); // 新增这行
});

方案3:同时忽略序列化返回(接口本身不需要返回嵌套属性时使用)

如果你接口本身也不需要返回这些导航属性,可以直接使用JSON序列化的忽略特性,会同时作用于接口返回和Swagger文档:

  • 若使用系统默认System.Text.Json序列化:标记[System.Text.Json.Serialization.JsonIgnore]
  • 若使用Newtonsoft.Json序列化:标记[Newtonsoft.Json.JsonIgnore]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:07