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

.NET API如何读取HTTP请求体中的camelCase格式JSON?

解决ASP.NET Core API无法接收camelCase请求体的问题

问题背景

你的API端点仅能处理PascalCase格式的请求体,使用camelCase时模型绑定失败,导致接口未进入处理逻辑。这是因为默认的System.Text.Json序列化器对属性名称大小写匹配要求严格。


解决方案1:开启大小写不敏感反序列化

在Program.cs中配置控制器的JSON选项,允许反序列化时忽略属性名称的大小写:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    });

配置后,无论请求体使用PascalCase还是camelCase格式,都能正确绑定到CreateSupplierCommand的属性,接口可正常调用。

解决方案2:显式指定请求体属性名

如果需要强制请求体使用camelCase,可以为模型属性添加JsonPropertyName特性:

using System.Text.Json.Serialization;

public class CreateSupplierCommand
{
    [JsonPropertyName("name")]
    public string Name { get; set; } = null!;
    
    [JsonPropertyName("website")]
    public string? Website { get; set; }
}

此方式会严格要求请求体使用指定的camelCase字段名,同时响应输出也会自动转为camelCase格式。

解决方案3:切换回Newtonsoft.Json(若之前使用)

若你在.NET 6中依赖Newtonsoft.Json(而非默认的System.Text.Json),可继续使用它(默认支持大小写不敏感):

  1. 先安装NuGet包:Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. 修改Program.cs配置:
builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        // 可选:配置响应输出为camelCase
        options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    });

原因说明

.NET 6及后续版本中,ASP.NET Core默认使用System.Text.Json作为JSON序列化器,它默认关闭了大小写不敏感匹配(PropertyNameCaseInsensitive = false)。而如果你之前在.NET 6中使用的是Newtonsoft.Json,它默认支持大小写不敏感反序列化,因此不会出现该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:05:26