在 Asp.net 核心 Web Api 中发布带有数组的对象

posting object with arrays in Asp.net core Web Api

我有 SPA 作为前端和 Asp.net 核心网络 api 作为后端。 我想 post 订单和 orderDetails 到 WebApi 并尝试在控制器中使用 OrderViewModel 来处理它。

edit:我发现了一个错误并解决了 orderDetails.cs 中的 it.that 模型 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; }
    }
}

模型中的 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中的postaction方法如下:

 [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: 对象引用未设置到对象的实例。 屏幕截图在这里: 该应用程序是一个在线商店,我想 post 将产品的订单和详细信息发送到后端以存储在数据库中。 提前感谢解决方法和帮助。

您的 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。