簡體   English   中英

POST 請求 vue C#

[英]POST request vue C#

---編輯問題:---

我正在用 c# web 應用程序作為后端和 Vue 作為前端構建我的第一個網站。 我的 GET 和 DELETE 工作正常,但是當我想運行 POST 時出現問題,我無法完全理解如何修復..

據我的老師說,我的 Axios 連接看起來不錯,問題僅出在我的后端..

我想我想做的是以某種方式綁定模型,以便他們互相交談?

我的數據模型是 Sale.cs,我的視圖模型(來自 Vue)被稱為 SaleVM.cs

銷售.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; }

    }
}

銷售VM:

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 內部服務器錯誤:

System.NullReferenceException:未將對象引用設置為對象的實例。 在 E37SalesApi.Controllers.SaleController.PostSale(SaleVM saleVM) 在 C:\\Users\\fadaka\\source\\repos\\E37SalesApi\\Controllers\\SaleController.cs:line 47 at lambda_method(Closure , Object) at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable。 Awaiter.GetResult() at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__AwaitedController|12Invoker0 invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker .Rethrow(ActionExecutedContextSealed context) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(Sta te& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() ---從上一個拋出異常的位置的堆棧跟蹤結束---在Microsoft.AspNetCore.Mvc。 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)的Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware context.Invoke(HttpContext context)

我確實明白它說的是什么,只是我真的不明白如何修復它並使我的 POST 方法完全起作用。

我希望我清楚我的問題

我對編程非常陌生,發現很難在網上找到像我這樣的菜鳥可以理解的水平的信息,尤其是在 c# 和 vue 一起工作時。

如果我是你,我會在 PostSale 操作的第一行放置一個斷點並檢查模型的哪些部分為空。

您的 JSON 中的屬性應該與您的模型相匹配。 UserId、StatusId、DateCreated 和 DateSold 都很好,但沒有其他東西通過,因此 SelectedCustomer 將為空(很可能會導致您的問題)。

{ 
  "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; }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM