0

I am having an issue with my Angular app. Basically the issue is that it displays a 500 server error.

These are my methods:

/*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);
  }
)}

And this is my C# method

[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"));
    }

And the error is the following:

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

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

Can somebody help me?

Thanks in advance.

HeyBaldur
  • 545
  • 1
  • 7
  • 16

2 Answers2

1

I found the issue by myself, the problem basically was that the endpoint expects to receive a well structured model, however in the HTML code there was an input with a 'text' type instead 'number', this seemed to affected the Angular interface. If somebody needs a asp.net core 3.1 with Angular 8 sample application please feel free to clone my repo to verify my code and learn more.

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

Thanks.

HeyBaldur
  • 545
  • 1
  • 7
  • 16
0

Your error is most likely caused by formdata not deserializing correctly, causing the NullReferenceException when accessing the members.

You would be able to catch this by checking if the ModelState.IsValid property is true before trying to access the members of formdata.

[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();
        }
    }
Matt Hensley
  • 908
  • 8
  • 18
  • I have debugged the method but it seems it's receiving a null value in the 'formdata' – HeyBaldur Dec 20 '19 at 16:37
  • Ok, this answer might be able to help you out with identifying why it is null. https://stackoverflow.com/questions/14084746/web-api-model-properties-are-null – Matt Hensley Dec 20 '19 at 16:39
  • Let me check it out. Thanks @Matt – HeyBaldur Dec 20 '19 at 16:41
  • Unfortunately I am still having issues. I have added JSON.stringify(newProduct), this.httpOptions but it now displays an 400 error. Here is my repo, https://github.com/gitrodo/asp-net-core-angular-8/tree/Development, maybe you can help me out with this. – HeyBaldur Dec 20 '19 at 17:42
  • I am not sure if the asp.net core version might affect. I am using the 3.0 version. – HeyBaldur Dec 20 '19 at 17:43
  • Does your ```Product``` class have any validation or data annotations on it that might not be being fulfilled? – Matt Hensley Dec 20 '19 at 19:47
  • Sure it does https://github.com/gitrodo/asp-net-core-angular-8/blob/master/Models/Product.cs – HeyBaldur Dec 20 '19 at 20:11