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

如何在Swagger Codegen中包含列表属性?解决Axios模型缺失ComplexItems问题

解决Swagger Codegen缺失List属性的问题

以下是针对该问题的具体解决方案:

1. 修复ExcludeNullableSchemaFilter过滤器

你配置的ExcludeNullableSchemaFilter可能错误地将ComplexItems集合属性当作可空属性过滤掉了。即使你初始化了集合,在启用Nullable引用类型的项目中,List<ComplexItem>仍会被标记为可空类型,导致被过滤器移除。

修改过滤器逻辑,保留集合类型的可空属性:

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

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

        // 仅移除非集合类型的可空属性
        var propertiesToRemove = schema.Properties
            .Where(p => 
                p.Value.Nullable 
                && !IsCollectionType(GetPropertyType(context.Type, p.Key)))
            .Select(p => p.Key)
            .ToList();

        foreach (var propertyName in propertiesToRemove)
        {
            schema.Properties.Remove(propertyName);
        }
    }

    private bool IsCollectionType(Type type)
    {
        // 排除string(string本身实现了IEnumerable<char>)
        return typeof(System.Collections.IEnumerable).IsAssignableFrom(type) && type != typeof(string);
    }

    private Type GetPropertyType(Type modelType, string propertyName)
    {
        return modelType.GetProperty(propertyName)?.PropertyType ?? typeof(object);
    }
}

2. 确保ComplexItem被Swagger识别

如果API端点中没有直接或间接引用ComplexItem,Swagger不会生成它的Schema,导致DummyModel的ComplexItems无法被正确描述。可以通过以下两种方式解决:

方式一:添加引用ComplexItem的端点

在Controller中新增一个简单端点,让Swagger检测到该类型:

[HttpGet("ComplexItemSample")]
public ComplexItem GetComplexItemSample()
{
    return new ComplexItem();
}

方式二:手动注册ComplexItem Schema

在AddSwaggerGen配置中手动定义ComplexItem的Schema:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SchemaFilter<ExcludeNullableSchemaFilter>();

    // 手动注册ComplexItem的Schema
    c.MapType<ComplexItem>(() => new OpenApiSchema
    {
        Type = "object",
        Properties = new Dictionary<string, OpenApiSchema>
        {
            {"id", new OpenApiSchema { Type = "string", Format = "uuid" }},
            {"property1", new OpenApiSchema { Type = "integer", Format = "int32" }},
            {"property2", new OpenApiSchema { Type = "string" }},
            {"property3", new OpenApiSchema { Type = "string", Format = "date-time" }}
        }
    });
});

3. 标记ComplexItems为非可空(针对Nullable引用类型项目)

如果项目启用了Nullable引用类型(.NET 6+默认启用),给ComplexItems添加[NotNull]属性,明确告知Swagger该属性不会为null:

using System.Diagnostics.CodeAnalysis;

public class DummyModel
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [NotNull]
    public List<ComplexItem> ComplexItems { get; set; } = new List<ComplexItem>();
}

4. 验证Swagger文档

修改完成后启动项目,访问/swagger/v1/swagger.json,检查DummyModel的Schema是否包含complexItems属性。若swagger.json中已出现该属性,重新运行Swagger Codegen即可生成包含该属性的TypeScript接口。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:23:22