使用Axios传数据时CustomerInfo后端接收为null的问题排查
解决Axios Post请求后端参数接收为null的问题
你的问题核心在于请求体格式与后端参数绑定方式不匹配:Axios默认发送JSON格式请求体,但后端未指定从JSON body中读取参数,导致无法正确绑定。以下是几种可行的修复方案:
方案1:后端定义DTO类接收JSON参数
定义一个与前端发送结构匹配的DTO,并用[FromBody]标记参数,让后端从JSON请求体中解析数据:
后端修改代码
// 新增DTO类 public class CustomerRequestDto { public string CustomerInfo { get; set; } } [HttpPost] public async Task AddNewCustomer([FromBody] CustomerRequestDto request) { // 这里request.CustomerInfo就能拿到前端传的JSON字符串了 string customerData = request.CustomerInfo; }
前端代码无需修改
保持你当前的Axios调用即可,因为前端已经把CustomerInfo包裹在JSON对象中发送。
方案2:前端直接发送字符串,后端用[FromBody]接收
如果不想定义DTO,可以让前端直接发送JSON字符串,后端指定从请求体读取:
前端修改代码
submit: function () { const $this = this; axios.post('/Customer/AddNewCustomer', JSON.stringify(this.DataInformation), { headers: { 'Content-Type': 'application/json' } }) .then(function (response) { location.reload(); }) .catch(function (error) { console.error(error); }); }
后端修改代码
[HttpPost] public async Task AddNewCustomer([FromBody] string CustomerInfo) { // 这里CustomerInfo就是前端传入的JSON字符串 }
方案3:前端发送FormData,后端用[FromForm]接收
如果希望用表单格式传递参数,可以调整前端发送FormData,后端指定从表单读取:
前端修改代码
submit: function () { const $this = this; const formData = new FormData(); formData.append('CustomerInfo', JSON.stringify(this.DataInformation)); axios.post('/Customer/AddNewCustomer', formData) .then(function (response) { location.reload(); }) .catch(function (error) { console.error(error); }); }
后端修改代码
[HttpPost] public async Task AddNewCustomer([FromForm] string CustomerInfo) { // 这里CustomerInfo就能拿到对应的值 }
问题原因说明
默认情况下,ASP.NET Core的string类型参数会尝试从查询字符串或表单数据中绑定值,但你的前端通过Axios发送的是application/json格式的请求体,后端没有指定从JSON body读取,所以无法匹配到参数,最终接收为null。通过上述方案明确参数绑定来源,就能解决这个问题。
内容的提问来源于stack exchange,提问作者user2432361
相关产品推荐
相关产品推荐

