'Bad Request: Angular service call to ASP.Net CORE Web API

I have an angular service that is called on a form submit. However when I try to pass a complex object public NewDogCreation(dog: Dog), its returning a 400 Bad Request. If I change the signature of the method to return a simple string or int public NewDogCreation(Id: any), the service call hits the web api method without issue and stops on my break point in visual studio. Postman also runs the api request successfully when passing a simple property to the web api controller.

Here is the entirety of my code:

Angular Service

      //Create New Dog Method
  public NewDogCreation(dog: Dog): Observable<Dog> {
    console.log('service data = '+ JSON.stringify(dog));
    let apiRoute = this.url + '/' + 'AddNewCanine';
    let attempts: any;
    return this.http.post<Dog>(apiRoute, dog)
      .pipe(
        map((dog: Dog) => { return dog; }));    
  } //end of NewDogCreation

.Net Core Web API Controller Action

 //Add Individual Dog
    [HttpPost]
    [Route("api/CanineManagement/AddNewCanine")]
    public IActionResult AddCanine([FromBody] Dog dog)
    {
        var dogObject = dog;
        var response = "Response success"; 
        return Ok(response);
    }//end of Add Dog API Method

CORS in Web API Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else { }
        app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        //app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

Any constructive input would be appreciated!



Solution 1:[1]

try this

const headers = new HttpHeaders().set('Content-Type','application/json');
  return this.http.post<Dog>(apiRoute, JSON.stringify(dog),{headers:headers})
  ....

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge