Asp.net CORE 3.0 Web API方法始终接收NULL值

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

我的Angular应用出现问题。基本上,问题是它显示500服务器错误。

这些是我的方法:

/*Product Service*/
addNewProduct(newProduct: Product): Observable<Product> {
console.log(newProduct);
return this.http.post<Product>(this.productUrl, newProduct);
}


/*Product-list.component.ts*/
onSubmit() {
let newProduct = this.insertForm.value;
console.log(newProduct);
this.productService.addNewProduct(newProduct).subscribe(
  result => {
    this.productService.clearCache();
    this.products$ = this.productService.getProducts();

    this.products$.subscribe(newlist => {
      this.products = newlist;
      this.modalRef.hide();
      this.insertForm.reset();

    });
    console.log("New Product added");
  },
  error => {
    console.error(error);
  }
)}

这是我的C#方法

[HttpPost("[action]")]
    [Authorize(Policy = "RequiredAdministratorRole")]
    public async Task<ActionResult> AddProduct([FromBody] Product formdata)
    {
        var newproduct = new Product
        {
            Name = formdata.Name,
            Description = formdata.Description,
            ImageURL = formdata.ImageURL,
            OutOfStock = formdata.OutOfStock,
            Price = formdata.Price
        };

        await _db.Products.AddAsync(newproduct);
        await _db.SaveChangesAsync();

        return Ok(new JsonResult("The product has been added successfully"));
    }

错误如下:

HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "OK", url: "https://localhost:44382/api/product/addproduct", ok: false, …}

POST https://localhost:44382/api/product/addproduct 500

有人可以帮我吗?

谢谢。

angular asp.net-core http-post
2个回答
0
投票

您的错误很可能是由于formdata无法正确反序列化,导致在访问成员时导致NullReferenceException。

您可以通过尝试访问formdata的成员之前检查ModelState.IsValid属性是否为true来捕获此错误。

[HttpPost("[action]")]
    [Authorize(Policy = "RequiredAdministratorRole")]
    public async Task<ActionResult> AddProduct([FromBody] Product formdata)
    {
        if (ModelState.IsValid)
        {
            var newproduct = new Product
            {
                Name = formdata.Name,
                Description = formdata.Description,
                ImageURL = formdata.ImageURL,
                OutOfStock = formdata.OutOfStock,
                Price = formdata.Price
            };

            await _db.Products.AddAsync(newproduct);
            await _db.SaveChangesAsync();

            return Ok(new JsonResult("The product has been added successfully"));
        }
        else
        {
            // Let the client know the data they passed was not valid.
            return BadRequest();
        }
    }

0
投票

我自己发现了问题,问题基本上是端点希望收到结构良好的模型,但是在HTML代码中,输入的类型为“文本”而不​​是“数字”,这似乎影响了Angular接口。如果有人需要带有Angular 8示例应用程序的asp.net core 3.1,请随时克隆我的存储库以验证我的代码并了解更多信息。

https://github.com/gitrodo/asp-net-core-angular-8

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