POST请求Vue C#

问题描述 投票:0回答:1

---编辑问题:---

我正在建立我的第一个网站,其中将c#Web应用程序作为后端,将Vue作为前端。我的GET和DELETE工作正常,但是当我想运行POST时遇到问题,我无法完全理解如何解决。.

根据我的老师,我的Axios连接看起来很好,而且问题仅在我的后端。.

我想我想做的就是以某种方式绑定模型,以便它们彼此交谈?

我的数据模型是Sale.cs,我的视图模型(来自Vue)叫做SaleVM.cs

Sale.cs:

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

namespace Models
{
    public class Sale
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; } //++
        [Required]
        public string CustomerNumber { get; set; }
        public int UserId { get; set; } //fk
        [Required]
        public string YourReference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime? DateDone { get; set; }
        public DateTime? DateEdited { get; set; }
        public Status StatusId { get; set; }
        public DateTime? DateDelivered { get; set; }

        public virtual ICollection<SaleArticle> SaleArticles { get; set; }
        public virtual User User { get; set; }

    }
}

SaleVM:

using System.Collections.Generic;

namespace Models
{
    public class SaleVM
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        public int Id { get; set; }
        public string Reference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public Status StatusId { get; set; }
        public int UserId { get; set; }

        public virtual ICollection<ArticleRow> ArticleRows { get; set; }
        public virtual SelectedCustomer SelectedCustomer { get; set; }

    }
}

我认为我把它们做错了,因为我只猜怎么写。

最后是我的SaleController:

{
    [Route("api/[controller]")]
    [ApiController]
    public class SaleController : ControllerBase
    {
        private readonly DataContext _context;

        public SaleController(DataContext context)
        {
            _context = context;
        }

        // POST: api/Sales/5
        [HttpPost]
        public async Task<ActionResult<Sale>> PostSale(SaleVM saleVM)
        {
          string customerNumber = (saleVM != null && saleVM.SelectedCustomer != null && Convert.ToInt32(saleVM.SelectedCustomer.CustomerNumber) > 0) ? saleVM.SelectedCustomer.CustomerNumber : "";

          List<SaleArticle> saleArticles = new List<SaleArticle>();
            if (saleVM != null && saleVM.ArticleRows != null && Convert.ToInt32(saleVM.ArticleRows) > 0)
            {
                foreach (var item in saleVM.ArticleRows)
                {
                    saleArticles.Add(new SaleArticle()
                    {
                        ArticleNumber = item.ArticleNumber,
                        Price = item.SalesPrice,
                        Quantity = item.Quantity,
                        Description = item.Description,
                        Id = item.Name
                    });
                }
            }
            //foreach (var saleVM in SaleVM)
            //{
            Sale sale = new Sale();
            {
                sale.CustomerNumber = saleVM.SelectedCustomer.CustomerNumber;
                sale.YourReference = saleVM.Reference;
                sale.SaleArticles = saleArticles;
                sale.DateCreated = saleVM.DateCreated;
                sale.DateSold = saleVM.DateSold;
                sale.StatusId = (Sale.Status)saleVM.StatusId;
                sale.UserId = saleVM.UserId;
            };

            _context.Sales.Add(sale);
            //}

            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetSale), new { id = saleVM.Id }, saleVM);
        }
    }
 }

我在Visual Studio中没有收到任何错误消息,但是当我在邮递员中尝试该代码时,我得到了状态码500 Internal Server Error:

System.NullReferenceException:对象引用未设置为对象的实例。在E37SalesApi.Controllers.SaleController.PostSale(SaleVM saleVM)中的C:\ Users \ fadaka \ source \ repos \ E37SalesApi \ Controllers \ SaleController.cs:第47行在lambda_method(Closure,Object)在Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()在Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper映射器,ObjectMethodExecutor执行器,对象控制器,Object []参数)在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited | 12_0(ControllerActionInvoker调用程序,ValueTask`1 actionResultValueTask)在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited | 10_0(ControllerActionInvoker调用程序,Task lastTask,Next状态,Scope作用域,对象状态,布尔值isCompleted)在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed上下文)在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和isCompleted)处在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()---从之前引发异常的位置开始的堆栈结束跟踪---在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited | 19_0(ResourceInvoker调用程序,Task lastTask,Next状态,Scope作用域,对象状态,Boolean isCompleted)在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited | 17_0(ResourceInvoker调用程序,任务任务,IDisposable范围)在Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask | 6_0(端点端点,任务requestTask,ILogger记录器)在Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)

我确实理解它的意思,只是我无法真正理解如何解决它并使我的POST方法完全起作用。

我希望我对我的问题很清楚

我对编程非常陌生,很难在网上找到像我这样的菜鸟可以理解的水平的信息,尤其是在c#和vue协同工作时。

c# vue.js http-post postman http-status-code-500
1个回答
0
投票

如果我是您,我会在您的PostSale操作的第一行上放置一个断点,并检查模型的哪些部分为空。

JSON中的属性应该与您的模型匹配。 UserId,StatusId,DateCreated和DateSold都可以,但是没有其他任何传递,因此SelectedCustomer将为null(最有可能导致您的问题)。

{ 
  "customerNumber": "111",
  "userId": 2,
  "yourReference": "Referens namn",
  "dateSold": "2020-03-01T00:00:00",
  "dateCreated": "2020-03-01T00:00:00",
  "dateDone": "2020-03-01T00:00:00",
  "dateEdited": "2020-03-01T00:00:00",
  "statusId": 2,
  "dateDelivered": "2020-03-01T00:00:00"
}

应与下面的位置匹配,即在那里'

public class SaleVM
{
    public enum Status
    {
        Started,
        Ongoing,
        Done,
        Removed
    }

    public int Id { get; set; }
    public string Reference { get; set; }
    public DateTime DateSold { get; set; }
    public DateTime DateCreated { get; set; }
    public Status StatusId { get; set; }
    public int UserId { get; set; }

    public virtual ICollection<ArticleRow> ArticleRows { get; set; }
    public virtual SelectedCustomer SelectedCustomer { get; set; }

}
© www.soinside.com 2019 - 2024. All rights reserved.