在 Asp.net core Web Api 中使用数组发布对象

问题描述

我有 SPA 作为前端和 Asp.net 核心 web api 作为后端。 我想将订单和订单详细信息发布到 WebApi 并尝试在控制器中使用 Orderviewmodel 处理它。

edit:我发现了一个错误解决了它。在 orderDetails.cs 模型中 Qty 应该更改为 Amount 并尝试但同样的错误也发生了截图附上。

json 请求负载如下:

{
Email: "fiazmianwal@gmail.com"
address: "1km mianwal road kuthiala sheikhan"
city: "mandi bahauddin"
customerName: "fiaz ahmed"
discount: 0
mobile: "03466469074"
orderDetails: [{productId: 1,productName: "shalwarqamees",productCode: "101",discount: 200,amount: 1,…},…]
qty: 3
total: 1800
whatsapp: "03466469074"}

后端的 order.cs 模型如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApi.Models
{
   
    public partial class Order
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int OrderId { get; set; }
        public int Qty { get; set; }
        [required]
        [StringLength(160)]
        public string CustomerName { get; set; }
        [required]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
        [required]
        [DataType(DataType.PhoneNumber)]
        public string Mobile { get; set; }

        [DataType(DataType.PhoneNumber)]
        public string Whatsapp { get; set; }
        [required]
        [StringLength(100)]
        public string City { get; set; }
      [required]
        [DataType(DataType.MultilineText)]
        public string Address { get; set; }
        public int StoreId { get; set; }
        public long ShopId { get; set; }
        [StringLength(70)]
        public string Status { get; set; }

        public decimal Total { get; set; }
       
        public decimal discount { get; set; }
        [DataType(DataType.Date)]
        [displayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yyyy}")]
        public System.DateTime UpdatedOn { get; set; }

    }
}

这是 oderDetails.cs 模型:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApi.Models
{
    public class OrderDetail
    {
        public int OrderDetailId { get; set; }
      
        public int ProductId { get; set; }
        public int Qty { get; set; }
        public string ProductCode { get; set; }
        public string ProductName { get; set; }
        public int StoreId { get; set; }    
        public string Unit { get; set; }
        public decimal Price { get; set; }
        public decimal discount { get; set; }

        public string Currency { get; set; }
    }
}

Models 中的 Orderviewmodel.cs 如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApi.Models
{
    public class Orderviewmodel
    {
        public Order Order { get; set; }
        public List<OrderDetail> OrderDetails { get; set; }
    }
}

orderscontroller 中的 post action 方法如下:

 [HttpPost]
        public async Task<ActionResult<Orderviewmodel>> postorder(Orderviewmodel order)
        {

           
         var ord = order.Order;  //save order in ord variable from orderviewmodel
            ord.UpdatedOn = DateTime.UtcNow;
            _context.Order.Add(ord); // here is null reference error
            var od = order.OrderDetails.ToList(); // get all orderdetails array of objects from orderviewmodel
            foreach (var d in od)     
            {
                _context.OrderDetails.Add(d);  //enter all products  details  in orderdetails table
            }
            await _context.SaveChangesAsync();

            return CreatedAtAction("Getorder",new { id = ord.OrderId },order);
        }

错误如下: System.NullReferenceException:未将对象引用设置为对象的实例。 截图在这里

screenshot of error in controller

该应用程序是一个在线商店,我想将产品的订单和详细信息发布到后端以存储在数据库中。 提前感谢您提供解决方法和帮助。

解决方法

您的 JSON 与您的视图模型不匹配。所以我的猜测是因为您没有在 JSON 中指定订单对象。在您的视图模型中,Order 将为 null 并且您在此行 ord.UpdatedOn = DateTime.UtcNow;

处获得 null 异常

尝试这样的事情

{
  "order": {
    "Email": "YourEmail@gmail.com","address": "1km mianwal road kuthiala sheikhan","city": "mandi bahauddin","customerName": "fiaz ahmed","discount": 0,"mobile": "********","qty": 3,"total": 1800,"whatsapp": "********"
  },"orderDetails": [
    {
      "productId": 1,"productName": "shalwarqamees","productCode": "101","discount": 200,"amount": 1,"…"
    },{
      "productId": 2,"productName": "asdqwesdasdasd","productCode": "201","discount": 300,"amount": 2,"…"
    }
  ]
}

顺便说一下,将 dbContext 的模型直接暴露给前端并不是一个好习惯。考虑在中间使用 DTO 或 POCO。