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

POST请求返回null但GET请求返回正确对象的问题排查

问题分析与解决

你的问题出在POST请求的参数传递和后端接收逻辑不匹配:

核心原因

  • 你在Ajax里设置了contentType: "application/json",但传递的data是普通JS对象,jQuery默认不会自动将其转为JSON字符串,导致后端无法正确解析参数,Id值为int类型默认值0,所以_uWebsitesService.GetWebsite(Id)返回null。
  • GET请求时参数通过URL查询字符串传递,后端能直接绑定到Id参数,因此可以返回正确对象。

两种解决方案

方案1:修正Ajax的JSON数据格式

将Ajax的data转为JSON字符串,同时后端参数添加[FromBody]标记:

修改后的Ajax代码:

$(".edit-website-btn").on("click", function () {
    let id = $(this).attr('data-id');
    $.ajax({
        type: "POST",
        url: "/userpanel/GetWebsite/",
        data: JSON.stringify({ Id: id }), // 转为JSON字符串
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        },
    })
})

修改后的控制器代码:

[HttpPost]
public async Task<JsonResult> GetWebsite([FromBody] int Id) // 添加[FromBody]标记
{
    var website = await _uWebsitesService.GetWebsite(Id);
    return (website == null ? this.Json("Website Not Found") : this.Json(website));
}

方案2:使用表单格式提交(更简单)

去掉Ajax中的contentType: "application/json",让jQuery默认以application/x-www-form-urlencoded格式传递参数,后端无需修改:

修改后的Ajax代码:

$(".edit-website-btn").on("click", function () {
    let id = $(this).attr('data-id');
    $.ajax({
        type: "POST",
        url: "/userpanel/GetWebsite/",
        data: { Id: id },
        dataType: "json",
        // 移除contentType配置
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        },
    })
})

控制器代码保持你原来的即可,POST请求默认会从表单数据中绑定参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:36:23