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

ASP.NET Core Razor页面AJAX POST请求失败,始终返回400错误

解决ASP.NET Core Razor Pages AJAX POST返回400 Bad Request的问题

遇到400 Bad Request最常见的原因就是防伪令牌验证失败,结合你的代码,我帮你梳理几个关键修复点:

1. 确保AJAX请求携带防伪令牌

你已经在页面添加了@Html.AntiForgeryToken(),但AJAX请求里必须主动带上这个令牌才能通过[ValidateAntiForgeryToken]的验证。有两种常用方式:

方式一:通过请求头传递令牌(推荐JSON格式时使用)

先获取页面中的令牌值,然后在AJAX的headers里添加RequestVerificationToken:

// 获取页面生成的防伪令牌
const token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    type: "POST",
    url: "/CheckIn/Payment?handler=ProcessCCPayment",
    contentType: "application/json", // 发送JSON格式数据
    headers: {
        "RequestVerificationToken": token // 关键:添加防伪令牌头
    },
    data: JSON.stringify({
        AmountExtra: 100 // 替换成你的模型属性值
    }),
    success: function(result) {
        console.log("返回结果:", result);
    },
    error: function(xhr) {
        console.error("请求失败:", xhr.statusText);
    }
});

方式二:通过表单数据传递令牌(适合表单格式)

如果不需要发送JSON,直接把令牌和模型数据一起放到data里:

const token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    type: "POST",
    url: "/CheckIn/Payment?handler=ProcessCCPayment",
    // 默认content-type是application/x-www-form-urlencoded,无需额外设置
    data: {
        __RequestVerificationToken: token,
        AmountExtra: 100 // 对应CheckInPaymentModel的属性
    },
    success: function(result) {
        console.log("返回结果:", result);
    },
    error: function(xhr) {
        console.error("请求失败:", xhr.statusText);
    }
});

2. 检查模型绑定是否正确

确保你的CheckInPaymentModel类的属性是public且包含get/set方法,否则模型绑定会失败,也可能导致400错误:

public class CheckInPaymentModel
{
    public decimal AmountExtra { get; set; } // 必须有get和set
    // 其他属性...
}

3. 验证防伪令牌是否正确生成

打开页面的HTML源码,确认能看到类似这样的隐藏输入框:

<input name="__RequestVerificationToken" type="hidden" value="xxxxxxxxx">

如果没有生成,检查页面是否在form标签内(虽然@Html.AntiForgeryToken()不需要form,但确保页面没有其他问题导致令牌未生成)。

4. 确认路由路径正确

如果你的页面属于某个Area,或者路由有自定义配置,要确保AJAX的url路径正确,比如:

url: "/YourArea/CheckIn/Payment?handler=ProcessCCPayment"

按照上面的步骤调整后,应该就能解决400 Bad Request的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:07:50