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

ASP.NET Core 2.2升级Swagger后System.Text.Json序列化大小写问题

解决Swashbuckle.AspNetCore升级后Swagger文档属性名变为大驼峰的问题

问题原因

Swashbuckle.AspNetCore 6.x版本默认使用System.Text.Json生成Swagger文档,不再沿用旧版本依赖的Newtonsoft.Json,因此你之前针对Newtonsoft.Json的ContractResolver配置无法影响Swagger文档的属性命名格式。

两种全局解决方法

方法1:切换回Newtonsoft.Json生成Swagger文档

如果希望继续使用Newtonsoft.Json的序列化规则,需要安装Swashbuckle的Newtonsoft扩展包,并配置Swagger复用Mvc的Newtonsoft设置:

  1. 安装扩展包:
dotnet add package Swashbuckle.AspNetCore.Newtonsoft
  1. 在Startup.cs的ConfigureServices中配置:
// 保留原有的Newtonsoft驼峰配置
services.AddMvc()
    .AddJsonOptions(json => 
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

// 配置Swagger使用Newtonsoft.Json生成文档
services.AddSwaggerGen(c =>
{
    // 你的Swagger基础配置(如文档标题、版本等)
})
.AddNewtonsoftJson(); // 关键配置:启用Newtonsoft.Json支持

方法2:配置System.Text.Json实现小驼峰命名

如果想继续使用System.Text.Json,可以直接配置Swagger的Schema生成策略,同时同步API响应的序列化规则:

  1. 配置Swagger的属性命名策略:
services.AddSwaggerGen(c =>
{
    // 你的Swagger基础配置
    c.JsonSchemaGeneratorOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
  1. (可选)如果API接口的响应也需要小驼峰格式,同步配置Mvc的System.Text.Json选项:
services.AddMvc()
    .AddJsonOptions(options => 
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase);

效果验证

配置完成后重新生成的swagger.json会恢复为升级前的小驼峰格式:

"Geschlecht": {
    "type": "object",
    "properties": {
        "key": {
            "type": "integer",
            "format": "int32"
        },
        "displayName": {
            "type": "string",
            "nullable": true
        }
    },
    "additionalProperties": false,
    "description": ""
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:56:11