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

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()处理数据但无效。

错误原因

  1. 字段名不匹配:前端请求体中传的是List字段,但后端Author模型对应的属性是Lis(少了末尾的t),导致模型绑定失败,value对象为NULL。
  2. 类型不兼容:前端传的List是数组类型,后端模型中Lis是字符串类型,ASP.NET默认无法自动将数组转换为字符串,进一步导致绑定失败。
  3. 代码拼写错误:后端代码中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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:30:43