ASP.NET Razor Pages中从JavaScript发送JSON到C#时出现400 Bad Request错误
ASP.NET Razor Pages中从JavaScript发送JSON到C#时出现400 Bad Request错误
我来帮你排查这个400错误的问题,在Razor Pages里发JSON经常会踩这几个坑,咱们一步步来解决:
1. 先把后端的页面模型配置对
Razor Pages的POST接口有两个关键要求,少一个都会直接返回400:
- 首先,处理POST请求的方法必须加
[HttpPost]特性,而且接收JSON参数时必须加[FromBody]标记,不然服务器不知道从请求体里读取JSON数据。比如你的Index页面模型应该这么写:public class IndexModel : PageModel { [HttpPost] public IActionResult OnPost([FromBody] List<OrderItem> orderItems) { // 这里写你处理订单数据的逻辑 return new JsonResult(new { success = true }); } } - 然后,你的C#模型类(比如上面的
OrderItem)要和JSON的字段对应上。因为你的JSON用的是下划线命名(比如customer_name),而C#一般用帕斯卡命名(CustomerName),这时候要加[JsonPropertyName]特性做映射,不然模型绑定会失败:using System.Text.Json.Serialization; public class OrderItem { [JsonPropertyName("customer_name")] public string CustomerName { get; set; } [JsonPropertyName("mobile")] public int Mobile { get; set; } [JsonPropertyName("bookName")] public string BookName { get; set; } [JsonPropertyName("unit_price")] public int UnitPrice { get; set; } public int Quantity { get; set; } public int Discount { get; set; } public int Total { get; set; } }
2. 修正前端AJAX的几个关键细节
前端代码里有两个很容易忽略的点,直接导致400:
- 必须携带防伪造令牌:Razor Pages默认开启了防伪造验证,没带令牌的POST请求会直接被拒绝。你需要这么做:
- 在你的Index.cshtml页面里加一个隐藏域获取令牌:
@Html.AntiForgeryToken() - 在AJAX请求里把令牌放到请求头中:
const token = $('input[name="__RequestVerificationToken"]').val(); const data = [ { "customer_name": "Abdullah Al Mahmud", "mobile": 7654, "bookName": "Physics 1st paper", "unit_price": 250, "quantity": 1, "discount": 0, "total": 250 }, { "customer_name": "Abdullah Al Mahmud", "mobile": 7654, "bookName": "Physics 1st paper", "unit_price": 250, "quantity": 6, "discount": 0, "total": 1500 } ]; $.ajax({ url: '/Index', type: 'POST', contentType: 'application/json', headers: { 'RequestVerificationToken': token // 这里加令牌 }, data: JSON.stringify(data), // 必须把数组转成JSON字符串,不能直接传对象 success: function(response) { console.log('数据发送成功:', response); }, error: function(xhr) { console.log('错误详情:', xhr.responseText); } });
- 在你的Index.cshtml页面里加一个隐藏域获取令牌:
- 确保发送的是正确的JSON字符串:一定要用
JSON.stringify(data)把你的数组转换成JSON格式的字符串,不然AJAX会把数据转成表单格式发送,服务器解析失败就会返回400。
3. 最后检查数据类型匹配
比如你的JSON里mobile是数字7654,C#模型里对应的Mobile属性必须是int/long类型,不能是string;total是数字,C#属性也要是数值类型,类型不匹配也会触发400错误。
把这些点都检查一遍,基本上就能解决这个400 Bad Request的问题了。
备注:内容来源于stack exchange,提问作者TARIF
相关产品推荐
相关产品推荐

