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

Asp.Net C#中API Post方法数据插入空引用错误求助

解决Asp.Net C#接口批量插入时的空引用错误

错误原因

你的接口参数直接声明为List<Mobile_Book_Order>,但Postman发送的请求数据把数组包裹在了data字段中,导致ASP.NET的模型绑定无法正确解析参数,obj_add_data会被赋值为null。后续代码中访问obj_add_data.Count时就触发了“Object reference not set to an instance of an object”空引用异常。

解决方法

方法一:调整Postman请求数据结构

直接发送数组格式的请求体,不需要外层的data包裹:

[
    { 
      "challenId": "0124555",
      "userId": "enam01",
      "bookOrderDate": "2022-10-17T17:00:15.667",
      "bookAcCode": "A1BVB/2013",
      "bookName": "Vasa Binnas Uchhotor Bangla Bayakaron & Rochonariti",
      "bookQuantity": "6",
      "bookInitialPrice": 298,
      "bookTotalPrice": 1788,
      "orderCertifyedBy": "you",
      "orderConfirmBy": "me"
    },
    {
      "challenId": "0124555",
      "userId": "enam01",
      "bookOrderDate": "2022-10-17T17:00:15.678",
      "bookAcCode": "A1DQS/2014",
      "bookName": "Due Part Question Suggestion (Science)",
      "bookQuantity": "8",
      "bookInitialPrice": 51,
      "bookTotalPrice": 408,
      "orderCertifyedBy": "you",
      "orderConfirmBy": "me"
    }
]

注意:调整bookOrderDate格式为标准ISO8601格式(比如2022-10-17T17:00:15.667),确保日期能正确绑定到实体类的日期属性。

方法二:修改接口参数适配现有请求结构

  1. 创建一个用于接收请求的DTO类:
public class OrderBatchRequest
{
    public List<Mobile_Book_Order> data { get; set; }
}
  1. 修改接口方法,使用这个DTO作为参数,并增加空值检查:
[HttpPost] // 确保添加HttpPost特性,指定请求方法
public IHttpActionResult AddData(OrderBatchRequest request)
{
    if (request?.data == null)
    {
        return BadRequest("请求数据不能为空");
    }

    var response = this.Request.CreateResponse(HttpStatusCode.Created);
    string json = JsonConvert.SerializeObject(request.data);
            
    using (ALFDB_13Entities1 db = new ALFDB_13Entities1()) // 使用using自动释放上下文
    {
        db.Mobile_Book_Order.AddRange(request.data); // 用AddRange替代循环Add,更高效
        db.SaveChanges();
    }

    response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            
    return ResponseMessage(response);
}

额外注意事项

  • 确保Postman请求方法为POST,且Content-Type设置为application/json
  • 检查Mobile_Book_Order实体类的属性名称、类型与请求中的字段完全匹配(比如大小写、数据类型)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:20:27