I've been encountering an issue while trying to send data from Angular to my .NET Core API, as the received data always ends up being null. Take a look at my code:
Here is the Angular POST request:
public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
const body: string = JSON.stringify(categoryToInsert);
return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', categoryToInsert);
}
The structure of ICategoryDTO is as follows:
export interface ICategoryDTO {
Id: number;
Name: string;
}
export default ICategoryDTO;
//example object:
{Id: null, Name: "yyuyuy"}
On the .NET Core side, this is how my API endpoint appears:
[HttpPost("new")]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
[ProducesResponseType(409)]
[ProducesResponseType(500)]
public IActionResult CreateWithAuthor([FromBody] CategoryDTO data)
{
var a = 1;
return Ok(this._iCategoryBusiness.CreateWithAuthor(data));
}
The CategoryDTO class is defined as follows:
using System;
namespace Back.DTO
{
public class CategoryDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
}
The Issue: When I place a breakpoint at var a = 1
, the data
is always null when sending the post request from the front-end. However, it does work when using Swagger.
Attempts Made: I have attempted to stringify the object before passing it, without success. I also tried adding a header, both with and without stringifying the object, but that didn't resolve the issue either. Changing the Id
type in ICategoryDTO from string to number did not make any difference.
Here's the header setup I tried:
header = new HttpHeaders()
.set('Content-type', 'application/json');
Along with a request like this:
public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
const body: string = JSON.stringify(categoryToInsert);
return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', body, {headers: this.header});
}
Unfortunately, this method yielded the same result.
Uncertain about where I am going wrong.