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

ASP.NET MVC控制器参数JsonPropertyName不生效问题求助

解决ASP.NET MVC控制器接收JSON时属性绑定为null的问题

核心问题分析

你的问题主要来自三个关键点:

  1. 序列化特性与ASP.NET版本不匹配:不同版本的ASP.NET默认使用的JSON序列化库不同,对应的特性也不一样;
  2. JSON数据类型与模型属性类型不匹配:JSON中MyCustomJsonProperty是数字类型,而模型中myProperty是字符串类型,默认绑定逻辑无法自动转换导致绑定失败;
  3. 特性指定的属性名称错误:你曾尝试添加[JsonProperty("BatchNumber")],但JSON中的键是MyCustomJsonProperty,名称不匹配自然无法绑定。

针对性解决方案

1. 使用对应版本的序列化特性

根据你的ASP.NET版本选择正确的特性:

  • ASP.NET Core(.NET 5+):默认使用System.Text.Json,需保留[JsonPropertyName]特性且名称与JSON键一致:
using System.Text.Json.Serialization;

public class MyClass 
{
    [JsonPropertyName("MyCustomJsonProperty")]
    public string myProperty { get; set; }

    // 其他属性
}
  • 传统ASP.NET MVC(.NET Framework):默认使用Newtonsoft.Json(Json.NET),需替换为[JsonProperty]特性(注意命名空间):
using Newtonsoft.Json;

public class MyClass 
{
    [JsonProperty("MyCustomJsonProperty")]
    public string myProperty { get; set; }

    // 其他属性
}

2. 修复数据类型不匹配问题

JSON中MyCustomJsonProperty的值是123(数字类型),而模型属性是string类型,有两种处理方式:

  • 修改JSON数据:将数字转为字符串格式:
{
    "MyCustomJsonProperty": "123",
    "property1": 1,
    "property2": 2
}
  • 修改模型属性类型:如果业务允许,将myProperty改为int类型:
[JsonPropertyName("MyCustomJsonProperty")] // 或对应版本的特性
public int myProperty { get; set; }

3. 验证请求内容类型

确保请求的Content-Type头设置为application/json,否则ASP.NET MVC可能不会使用JSON绑定器处理请求体。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:15:06