Angular POST sends null to .NET Core API

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.

Answer №1

After spending a couple of hours troubleshooting, I finally found the solution by changing my Id parameter to be set as 0 instead of null. It seemed to make sense since it is non-nullable on the .NET side. Hopefully, this helps save someone else some time!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Implementing Angular functionality with Bootstrap's collapse component

I am currently learning Angular and experimenting with two collapsible div elements. My goal is to have element-1 collapse and element-2 hide when button1 is clicked. Conversely, when button2 is clicked, I want element-2 to collapse and element-1 to hide. ...

Leveraging a ScrollView in an AbsoluteLayout with Angular Nativescript

I have developed a unique photo browsing app that allows users to swipe between pages to view different photos. Currently, I have implemented a working view for this feature. <ScrollView orientation="horizontal" ios.pagingEnabled="true" > <Stac ...

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

How can I automatically update a div's value when adding or editing data in an SQL table?

I am currently working with MVC 5 .net and Entity Framework. My goal is to create a client dashboard that displays the latest data from a SQL database. Can anyone advise me on how to call an ajax method or refresh a specific table/div when any values are ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

Adding a unique font to the themeprovider within styled components: A step-by-step guide

In the process of developing a React application using material-ui styled-components along with TypeScript. The task at hand is to incorporate a custom font into my styled components, but I'm facing challenges in making it functional. My initial ste ...

Using Context to Populate a DataSet with Entity Framework 4

How can I extract data from a Context and use it to populate my DataSet in order to display it in a TreeView Control? I have retrieved the Data using spCmsCategoriesReadHierarchy function. My goal is to effectively transfer this Data into a DataSet for fu ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Creating a class and initializing it, then implementing it in other classes within an Angular application

Trying to grasp some angular fundamentals by creating a class structure. Unsure if this is the right approach. export class Cars{ Items:Car[]=[]; constructor() { this.Items = [ { id: "1", name: "Honda" ...

404 Error: Unable to Locate Socket Io

I'm currently working on implementing a chat feature in Angular 2 using Socket IO, following this tutorial. However, I encountered an error message during a test on the server: GET http://localhost:3000/socket.io/?EIO=3&transport=polling& ...

transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties. Here is the initial array: const json = [{ "ID": 10, "Sum": 860, "class": "K", }, { "ID": 10, "Sum": 760, "class": "one", }, { "ID": ...

Showcasing an Angular Material Dialog following a delay of x seconds

I'm currently working on integrating an Angular Material Dialog and I would like it to appear x seconds after the user clicks the openDialog button. Is this achievable? ...

Is it possible to combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

Retrieving data from dynamic form components in Angular

I am currently utilizing a back-end API to retrieve flight data, which I then iterate through and exhibit. The layout of my template code is as follows... <form novalidate #form="ngForm"> <div class="flight-table"> <header fxLayou ...

A data type that exclusively accepts values from an enumerated list without mandating the inclusion of every possible value within the enum

Here's a code snippet I'm working with: enum Foo { a, b, c } type Bar = { [key in keyof typeof Foo]: string; } const test: Bar = { a: 'a', b: 'b' }; I'm encountering an issue where the code is complaining ...

Tracking button clicks on Angular Material using Google Analytics through Google Tag Manager

I'm currently utilizing the Universal Analytics tag within Google Tag Manager to monitor user interactions. I'm looking to establish click listeners in GTM that will trigger when specific buttons on the page are clicked. These buttons are Angular ...

What's the best way to fix a div to the bottom left corner of the screen?

I have explored various solutions regarding this issue, but none of them seem to meet my specific requirements. What I am trying to achieve is the correct positioning of a div as depicted in the green area in the image. https://i.sstatic.net/O9OMi.png Th ...

Error: Angular version 5.1.0 is unable to set the header content-type to application/json for HttpClient

I have been attempting to customize the header for a POST API request to be of content type application.json. let options: { headers?: {'Content-Type':'application/json'} } Unfortunately, this customization is not being successfully a ...

Creating custom result formats through WCF to return JSONP

So, I have a WCF service that gives back a customized object with specific properties that I need to utilize. [DataContract] public class CommonJsonResponse { [DataMember] public object Data { get; set; } [DataMember] public bool Success ...