Axios POST请求致ASP.NET POST控制器方法获取NULL值问题排查
解决React Axios POST到ASP.NET后端时数据为NULL的问题
问题概述
通过React的Axios组件用POST方法向ASP.NET后端存储数据,Postman调用API正常,但前端发送的数据在后端POST控制器方法中显示为NULL,触发System.NullReferenceException: 'Object reference not set to an instance of an object.'异常,尝试过JSON.stringify()处理数据但无效。
错误原因
- 字段名不匹配:前端请求体中传的是
List字段,但后端Author模型对应的属性是Lis(少了末尾的t),导致模型绑定失败,value对象为NULL。 - 类型不兼容:前端传的
List是数组类型,后端模型中Lis是字符串类型,ASP.NET默认无法自动将数组转换为字符串,进一步导致绑定失败。 - 代码拼写错误:后端代码中
Datetime.now应为DateTime.Now(C#中DateTime是大写开头,Now首字母大写);且未对value做空值判断,当绑定失败时直接访问value.Data等属性会触发空引用异常。
修复步骤
前端代码修改
调整请求体字段名与后端模型一致,并将数组转换为JSON字符串:
var headers = { 'Authorization': 'Bearer ' + localStorage.getItem('tk'), 'Content-Type': 'application/json' } axios.post("https://localhost:8000/api/" + 'Author', { Data: this.state.books, // "Book1 (string)" Text: this.state.text, // "Douglas M (string)" Lis: JSON.stringify([1,2,3]) // 将数组转为JSON字符串,匹配后端string类型 }, {headers: headers}) .then((response) => { window.location.href = '/home'; }) .catch((error) => { console.log(error); });
后端代码修改
修正拼写错误,增加空值判断,确保模型绑定成功:
[Produces("application/json")] [HttpPost] public HttpResponseMessage Post([FromBody] Author value) { // 先判断value是否为null,避免空引用异常 if (value == null) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } Author input = new Author () { Data = value.Data, Text = value.Text, Lis = value.Lis, // 与模型属性名一致 Date = DateTime.Now // 修正拼写错误 }; _model.Author.Add(input); _model.SaveChanges(); return new HttpResponseMessage(HttpStatusCode.OK); }
模型确认
确保Author模型的属性名和类型正确:
public class Author { public string Data { get; set; } public string Text { get; set; } public string Lis { get; set; } // 存储数组的JSON字符串 public DateTime Date { get; set; } // 新增Date属性,需确保数据库表中有对应字段 }
额外说明
- 若希望后端直接处理数组转字符串,也可修改模型属性为
List<int>,后端接收后将数组转换为JSON字符串再存储,但需保证前后端字段名完全一致。 - 调试时可在前端浏览器控制台查看请求体内容,或在后端控制器中添加日志,确认请求数据是否正确到达。
内容的提问来源于stack exchange,提问作者retro_coder
相关产品推荐
相关产品推荐

