我的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
有人可以帮我吗?
谢谢。
您的错误很可能是由于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();
}
}
我自己发现了问题,问题基本上是端点希望收到结构良好的模型,但是在HTML代码中,输入的类型为“文本”而不是“数字”,这似乎影响了Angular接口。如果有人需要带有Angular 8示例应用程序的asp.net core 3.1,请随时克隆我的存储库以验证我的代码并了解更多信息。