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

ASP.NET Core中[FromBody]参数始终为Null的POST请求问题

ASP.NET Core Web API [FromBody]参数绑定为Null问题排查

开发ASP.NET Core Web API接口时,接收POST请求体JSON对象时,即使通过Swagger发送结构正确的请求,使用[FromBody]修饰的GetTransactionModel参数始终为Null。

控制器代码

[ApiController]
[Route("/api/user/[controller]/[action]")]
[Authorize(Roles = ServiceConstants.AuthenticationRoleUser)]
public class DamavandController : BaseController
{
    [HttpPost]
    public async Task<ActionResult<DamavandTransactionResult>> RequestTransactions([FromBody] GetTransactionModel transactionModel)
    {
        if (transactionModel == null)
        {
            _logger.LogError("Model binding failed: transactionModel is null.");
            return BadRequest("Model binding failed: transactionModel is null.");
        }

        var transactions = await GetDamavandComponent().GetTransactions(transactionModel.DateFrom, transactionModel.DateTo, transactionModel.TerminalNumber, transactionModel.Limit, transactionModel.Offset);

        return Ok(transactions);
    }
}

namespace DecaPay.Controllers
{
    [ApiController]
    [Produces("application/json")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public class BaseController : ControllerBase
    {
    }
}

模型类代码

public class GetTransactionModel
{
    public string DateFrom { get; set; }
    public string DateTo { get; set; }
    public long TerminalNumber { get; set; }
    public int Limit { get; set; } = 25;
    public int Offset { get; set; } = 0;
}

发送的JSON数据

{
  "DateFrom": "2024/08/19",
  "DateTo": "2024/08/20",
  "TerminalNumber": 123456,
  "Limit": 25,
  "Offset": 0
}

已尝试的操作

  • 添加[ApiController]特性启用自动模型绑定和验证
  • 确认Swagger中JSON payload结构与GetTransactionModel属性名称完全匹配
  • 为Limit和Offset设置默认值
  • 验证Swagger请求的Content-Type为application/json

排查解决建议

  • 检查JSON序列化配置:确认项目是否手动关闭了PropertyNameCaseInsensitive(默认开启),这会导致大小写不匹配时绑定失败。可在Program.cs中验证配置:
    builder.Services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        });
    
  • 查看模型绑定错误详情:在控制器中添加模型状态校验,输出具体错误信息:
    if (!ModelState.IsValid)
    {
        var errors = ModelState.SelectMany(x => x.Value.Errors.Select(e => e.ErrorMessage));
        _logger.LogError("Model validation failed: {Errors}", string.Join(", ", errors));
        return BadRequest(ModelState);
    }
    
  • 排除授权中间件干扰:临时移除[Authorize]特性测试,确认是否因授权失败导致模型绑定流程异常。
  • 验证请求体完整性:使用Postman/Fiddler重新发送请求,排除Swagger可能引入的隐藏格式问题(如不可见特殊字符)。
  • 确认模型构造函数:若后续给GetTransactionModel添加了带参构造函数,必须显式定义无参构造函数,否则模型绑定会失败。
  • 检查绑定源冲突:确保没有同时使用[FromQuery]等其他绑定特性,避免与[FromBody]的绑定逻辑冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:35:07