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

.NET 8控制器中获取带[JsonPropertyName]的属性值返回null求助

问题解决:.NET 8 API中[JsonPropertyName]绑定属性为null的处理方案

可能的原因及对应解决步骤

1. 确认JSON序列化器匹配

.NET 8 默认使用 System.Text.Json 作为序列化器,[JsonPropertyName] 是它的专属特性。如果项目引入了 Newtonsoft.Json(Json.NET)并配置为默认序列化器,该特性会直接失效。

  • 解决办法:
    • 若继续使用 System.Text.Json:确保项目未全局替换序列化器,可在Program.cs中确认并补充配置:
      builder.Services.AddControllers()
          .AddJsonOptions(options =>
          {
              // 可选:开启大小写不敏感匹配,避免键名大小写差异导致绑定失败
              options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
          });
      
    • 若改用 Newtonsoft.Json:将 [JsonPropertyName] 替换为 Newtonsoft 专属的 [JsonProperty] 特性:
      using Newtonsoft.Json;
      
      public class PropertyCollection
      {
          [JsonProperty("User Name:")]
          public string UserName { get; set; } = string.Empty;
      
          [JsonProperty("User Password:")]
          public string UserPassword { get; set; } = string.Empty;
      }
      

2. 验证请求的Content-Type与JSON格式

  • 必须确保请求的 Content-Type 请求头设置为 application/json,否则 [FromBody] 无法正确解析请求体内容。
  • 检查请求体的JSON键名与 [JsonPropertyName] 定义完全一致,包括空格、冒号和大小写(默认大小写敏感),示例正确请求体:
    {
        "User Name:": "test_user",
        "User Password:": "test_pass_123"
    }
    

3. 修正路由参数绑定(针对userId)

接口方法中的 userId 参数未在路由定义中声明,会导致该参数也无法正常绑定。如果 userId 是URL路径参数,修改路由配置:

[HttpPost("usersubmit/{userId}", Name = "user-data")]
[ServiceFilter(typeof(ValidateMediaTypeAttribute))]
public IActionResult PostUserData([FromBody] PropertyCollection UserCol, string userId)
{
    return new OkObjectResult(iUserDataHelper.PostUserData(UserCol, userId));
}

如果是查询参数,确保请求URL携带 ?userId=xxx 参数。

4. 排查ValidateMediaTypeAttribute过滤器逻辑

检查自定义的 ValidateMediaTypeAttribute 过滤器,确认它未拦截或误判 application/json 类型的请求,比如是否错误限制了允许的媒体类型,导致请求体未被正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:25:01