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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Bro, you saved my day. I added the JsonStringInputFormatter and it started working.
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();
        }
    }

7 Comments

I have debugged the method but it seems it's receiving a null value in the 'formdata'
Ok, this answer might be able to help you out with identifying why it is null. stackoverflow.com/questions/14084746/…
Let me check it out. Thanks @Matt
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, github.com/gitrodo/asp-net-core-angular-8/tree/Development, maybe you can help me out with this.
I am not sure if the asp.net core version might affect. I am using the 3.0 version.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.