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

.NET Core 3.1派生类重写父类属性时JSON特性不生效求助

解决.NET Core 3.1中Newtonsoft.Json子类重写属性Swagger显示异常问题

问题场景

使用.NET Core 3.1搭配Newtonsoft JSON.NET时,子类重写父类的virtual属性后出现以下异常:

  • 子类添加[JsonIgnore],Swagger仍显示父类的tags属性
  • 子类添加[JsonProperty(PropertyName = "test123")],Swagger同时显示原tags和新属性名test123

核心原因

Swashbuckle.AspNetCore默认使用System.Text.Json生成API Schema,而项目实际用Newtonsoft.Json处理序列化,两者规则不兼容,导致子类重写属性上的Newtonsoft特性未被Swagger正确识别。

解决方案

1. 安装适配的Swashbuckle Newtonsoft包

安装对应.NET Core 3.1的Swashbuckle.AspNetCore.Newtonsoft版本(5.x系列,如5.6.3):

Install-Package Swashbuckle.AspNetCore.Newtonsoft -Version 5.6.3

2. 配置Swagger使用Newtonsoft契约解析

在Startup.cs的ConfigureServices方法中,给Swagger添加Newtonsoft支持:

services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

// 配置Swagger并启用Newtonsoft支持
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API名称", Version = "v1" });
})
.AddSwaggerGenNewtonsoftSupport(); // 关键配置:让Swagger使用Newtonsoft的规则生成Schema

验证效果

  • 子类添加[JsonIgnore]重写Tags:Swagger中不再显示tags属性,符合预期
  • 子类添加[JsonProperty("test123")]重写Tags:Swagger中仅显示test123属性,原tags不再出现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:36:32