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

Ajax POST请求HomeController方法持续返回400 Bad Request错误求助

解决Ajax POST请求到ASP.NET Core控制器返回400 Bad Request的问题

方案一:使用DTO类配合[FromBody]绑定(推荐)

  1. 创建用于接收请求数据的DTO类:
public class AreaRequest
{
    public string Area { get; set; }
}
  1. 修改控制器方法,通过[FromBody]指定从请求体读取数据,并使用DTO作为参数:
[HttpPost]
public async Task<string> FindAreaCode([FromBody] AreaRequest request)
{
    string resp = request.Area + " - 01473";
    return resp;
}
  1. 保持原有Ajax代码不变(请求体JSON结构与DTO匹配):
$.ajax({
    url: '/home/findareacode',
    contentType: 'application/json',
    data: JSON.stringify({area: 'Ipswich'}),
    type: 'post',
    success: function (d) {
        alert("Response " + d);
    },
    error: function () {
        alert("error in finding areacode");
    }
});

方案二:直接绑定单个字符串参数(需调整请求格式)

  1. 给控制器参数添加[FromBody]特性:
[HttpPost]
public async Task<string> FindAreaCode([FromBody] string area)
{
    string resp = area + " - 01473";
    return resp;
}
  1. 调整Ajax的data部分,直接序列化字符串而非对象:
$.ajax({
    url: '/home/findareacode',
    contentType: 'application/json',
    data: JSON.stringify('Ipswich'),
    type: 'post',
    success: function (d) {
        alert("Response " + d);
    },
    error: function () {
        alert("error in finding areacode");
    }
});

方案三:使用表单格式传递数据(无需修改控制器参数)

如果不想用JSON格式,可改用表单数据传递,此时不需要[FromBody]:

  1. 保持控制器方法不变:
[HttpPost]
public async Task<string> FindAreaCode(string area)
{
    string resp = area + " - 01473";
    return resp;
}
  1. 修改Ajax代码,去掉contentType设置(默认使用application/x-www-form-urlencoded),直接传递对象:
$.ajax({
    url: '/home/findareacode',
    data: {area: 'Ipswich'},
    type: 'post',
    success: function (d) {
        alert("Response " + d);
    },
    error: function () {
        alert("error in finding areacode");
    }
});

错误原因说明

400错误的核心原因是:发送application/json格式的POST请求时,ASP.NET Core默认不会将请求体中的JSON绑定到简单类型参数(如string、int)上,必须通过[FromBody]显式指定从请求体读取数据;而GET请求正常是因为GET参数从URL查询字符串获取,框架默认支持绑定到简单类型参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:26:14