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

ASP.NET Core添加CSRF防护后JS调用控制器参数为空求助

解决ASP.NET Core中POST JSON参数绑定为null的问题

问题核心是请求内容类型和参数绑定方式不匹配:

  • 原$.post默认发送application/x-www-form-urlencoded格式数据,ASP.NET Core会自动从表单数据中绑定简单类型参数;
  • 改用fetch发送application/json格式的JSON字符串后,默认参数绑定规则不会从请求体的JSON中读取简单类型参数,导致所有参数为null。

有两种可行的解决方式:

方式一:给控制器参数添加[FromBody]属性

修改控制器方法,通过[FromBody]标记从JSON请求体绑定参数,需将参数封装为模型类(单个[FromBody]仅能绑定一个对象):

[HttpPost]
public async Task CallMe([FromBody] CallRequest request)
{
    var userLogin = HttpContext.Session.Get<UserLogin>("userLogin");
    if (userLogin != null)
    {
        var tokenModel = await GetSessionToken();
        // 使用 request.Destination、request.CallIndex、request.FromNumber
    }
}

// 定义对应请求模型类
public class CallRequest
{
    public string Destination { get; set; }
    public string CallIndex { get; set; }
    public string FromNumber { get; set; }
}

方式二:保持参数不变,修改请求格式为表单编码

若不想修改控制器代码,可将fetch的请求格式改回与原$.post一致的表单编码:

var data = new FormData();
data.append('destination', destination);
data.append('callIndex', callIndex);
data.append('fromNumber', fromNumber);

fetch("@Url.Action("CallMe")", {
    method: "POST",
    headers: {
        'RequestVerificationToken': document.getElementById("RequestVerificationToken").value
    },
    body: data
});

也可使用URLSearchParams构造表单数据:

var data = new URLSearchParams();
data.append('destination', destination);
data.append('callIndex', callIndex);
data.append('fromNumber', fromNumber);

fetch("@Url.Action("CallMe")", {
    method: "POST",
    headers: {
        'RequestVerificationToken': document.getElementById("RequestVerificationToken").value,
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: data
});

补充说明

  • 推荐使用方式一,JSON格式更适配复杂数据结构,符合RESTful API的常见设计规范;
  • 确保前端JSON属性名与后端模型属性名一致(默认大小写敏感,可通过配置修改绑定规则)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:55:17