0

I'm trying to POST data from Angular to my .NET Core API, but the incoming data is always null. See my code:

Here is my POST from Angular:

public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
        const body: string = JSON.stringify(categoryToInsert);
        return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', categoryToInsert);
    }

ICategoryDTO being an object like this:

export interface ICategoryDTO {
    Id: number;
    Name: string;
}
export default ICategoryDTO;

//exemple object:
{Id: null, Name: "yyuyuy"}

This is what my API endpoint looks like on the .NET Core side:

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

CategoryDTO being defined by this class:

using System;

namespace Back.DTO
{
    public class CategoryDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

My problem: I have a breakpoint at var a = 1 and on that breakpoint data is always null when performing the post from my front-end. Doing it from Swagger works.

What I have tried: I have tried to stringify my object before passing it, which did nothing. I have also tried to pass a header along, both with stringified and non-stringified object, which did not work either. I changed the ICategoryDTO Id type from string to number but that did nothing.

Here's the header I have tried:

header = new HttpHeaders()
    .set('Content-type', 'application/json');

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

Didn't work, same result.

Don't know what I'm doing wrong.

1
  • check your network tab in chrome when making the angular request, make sure that the headers for this request are what you expect them to be. Commented Jun 29, 2020 at 19:44

1 Answer 1

1

I fixed it by making my Id parameter not null, but 0 instead. I guess this makes sense because it isn't nullable on the .NET end. This took me two hours.

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

Comments

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.