在Visual Studio 2022/ASP.NET Core 5.0 MVC中用Ajax遇参数为空求助
解决ASP.NET Core 5.0中Ajax传参为空的问题
问题原因
ASP.NET Core 5.0对模型绑定规则的严格性高于早期版本,同时标准JSON要求必须用双引号包裹键值对;此外当请求contentType设置为application/json时,必须明确指定从请求体绑定参数,否则框架会默认从表单或URL查询字符串中读取,导致参数为空。
解决方案
1. 修正前端Ajax参数格式
推荐使用JSON.stringify()将JS对象序列化为标准JSON字符串,避免手动拼接格式错误:
function Load() { $.ajax({ type: "POST", url: "/Attendence/GetData", dataType: "json", data: JSON.stringify({ name: "lavlesh" }), contentType: 'application/json; charset=utf-8', success: function(res) { alert(res); }, error: function(res) { alert(res.responseText); // 显示具体错误信息便于排查 } }); }
如果坚持手动编写JSON字符串,需确保使用双引号:
data: '{"name":"lavlesh"}',
2. 后端Action添加[FromBody]特性
当请求内容类型为application/json时,必须通过[FromBody]告知ASP.NET Core从请求体中读取参数:
情况1:直接接收字符串参数
[HttpPost] public IActionResult GetData([FromBody] string name) { return Json(name); }
情况2:接收实体类参数(更规范)
先定义实体类:
public class AttendenceRequest { public string Name { get; set; } }
再修改Action:
[HttpPost] public IActionResult GetData([FromBody] AttendenceRequest request) { if (request == null || string.IsNullOrEmpty(request.Name)) { return BadRequest("参数无效"); } return Json(request.Name); }
说明
早期ASP.NET Core版本可能兼容单引号这类不规范的JSON格式,但ASP.NET Core 5.0严格遵循JSON标准,同时模型绑定规则更明确,必须满足上述两个条件才能正确接收参数。
内容的提问来源于stack exchange,提问作者Lavlesh Jaiswal
相关产品推荐
相关产品推荐

