【问题标题】:posting object with arrays in Asp.net core Web Api在 Asp.net 核心 Web Api 中发布带有数组的对象
【发布时间】:2021-07-15 16:57:43
【问题描述】:

我有 SPA,其中 react 作为前端,Asp.net 核心 web api 作为后端。 我想将订单和 orderDetails 发布到 WebApi 并尝试在控制器中使用 OrderViewModel 处理它。

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

json请求payload如下:

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

【问题讨论】:

  • 你能确定 _context 已初始化且不为空吗?
  • 嗨@subhankars 感谢您的帮助和对我的问题的兴趣。我已将 orderDetails.cs 模型属性从 qty 修复为 amount 并尝试但同样的错误。我编辑了问题,请检查。
  • 你确定 null 异常不在ord.UpdatedOn = DateTime.UtcNow; 行吗?
  • 问题解决了吗?

标签: c# asp.net-core-webapi single-page-application webapi asp.net-mvc-viewmodel


【解决方案1】:

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

试试这样的

{
  "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。

【讨论】:

  • 嗨@MrMoeinM 感谢您解决我的问题。请原谅我迟到的回复。我按照您的描述修改了 json 模型,并进行了更多更改,它解决了我的问题。非常感谢。
猜你喜欢
  • 2018-01-16
  • 2017-01-05
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
相关资源
最近更新 更多