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

在Razor Pages中使用AJAX发送POST请求时遭遇400错误的排查

ASP.NET Core Razor Pages AJAX POST请求返回400错误排查

问题

尝试通过AJAX发送POST请求到Razor Pages页面时,持续收到400状态码错误。GET请求可正常触发后端断点,POST请求无法进入方法。

后端代码

namespace xx.WebApp.Pages.Dependency
{
    public class CreateModel : PageModel
    {        
        public IActionResult OnGet(string test) {
            return Page();
        }

        [HttpPost]
        public async Task<IActionResult> OnPostAsync([FromBody] CreateDependencyRequest createDependencyRequest) {
            return new JsonResult("Test");
        }
    }
}

正常工作的GET请求AJAX代码

$.ajax({
    url: `/Dependency/Create?test=1`,
    type: 'GET',
    dataType: 'json',                
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

报错的POST请求AJAX代码

$.ajax({
    url: `/Dependency/Create`,
    type: 'POST',
    dataType: 'json',                
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

解决方案

  • 移除[HttpPost]特性:Razor Pages的处理方法通过命名约定(如OnPostAsync)识别请求类型,[HttpPost]是MVC控制器的特性,添加到PageModel方法会导致路由匹配异常,直接删除即可。
  • 添加防伪造令牌:Razor Pages默认启用防伪造验证,AJAX POST请求必须携带验证令牌。
    1. 在页面中添加隐藏字段:
      <input asp-for="__RequestVerificationToken" type="hidden" />
      
    2. 在AJAX请求中加入请求头:
      $.ajax({
          // 其他配置不变
          headers: {
              "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
          }
      });
      
  • 验证模型绑定:400错误多由模型绑定失败导致,检查formData的结构、字段名(大小写敏感)、数据类型是否与CreateDependencyRequest类完全匹配。可在后端添加验证逻辑排查:
    public async Task<IActionResult> OnPostAsync([FromBody] CreateDependencyRequest createDependencyRequest) {
        if (!ModelState.IsValid)
        {
            return new JsonResult(ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage)));
        }
        return new JsonResult("Test");
    }
    
  • 确认路由与请求方法:确保POST请求的URL正确指向/Dependency/Create,请求方法为POST,无路由规则或中间件干扰请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:39