My requests and responses will undergo changes in naming conventions without my consent or awareness

Initially, I wrote it in a somewhat general manner. If you require more information, please let me know!

This is how my C# class appears when sent/received on the frontend:

    public class Recipe : ICRUD
    {       
        public Guid ID { get; set; }
        public Guid UnitID { get; set; }
        public string Title { get; set; }
        // ...plus Lists...
    }

[Backend => Frontend]

Backend

 [HttpGet("Recipe/[action]")]
 public async Task<JsonResult> GetRecipes(ServerRequest filter)

Frontend

   getRecipes(filter: ServerRequest) {
        return this._http.get(this.myAppUrl + 'Recipe/GetRecipes' + '?' + this.toQueryString(filter))
            .pipe(map((res: Recipe[]) => { return res; }));
    }

Upon observing my network traffic, something altered the model:

ID => id
UnitID => unitId 
// ...plus Lists...

Consequently, I updated my (frontend, typescript) model accordingly:

export class Recipe {
    id: string;
    unitId: string;
    title: string; 
}

Now that I have reached a stable state, I aim to send the data back to the server.

Next issue:

[Frontend => Backend]

Frontend

createRecipe(recipe: Recipe) {
        return this._http.post(this.myAppUrl + 'Recipe/CreateRecipe', recipe)
            .pipe(map(res => { return res; })); 

Backend

[HttpPost("Recipe/[action]")]
public async Task<HttpResponseMessage> CreateRecipe([FromBody]Recipe recipe)

Guess what?

ModelState is invalid because it is missing UnitID - yes, because it's written as unitId

The system expects a capital letter(UnitID), but I am sending unitId, so UnitID ends up being null (at least, that's my explanation)?

What should I do?

Answer №1

Unknown to you, it is the JSON serializer converting your data without your awareness. In ASP.NET Core, the default JSON serializer transforms pascal cased C# types into camel cased JSON. For example, if we take this C# class as an instance:

class Recipe
{
    public Guid ID { get; set; }
    public Guid UnitID { get; set; }
}

it will be represented in JSON like this:

{
    "id": "...",
    "unitID": "..."
}

The process reverses when binding JSON to a C# class. Note the distinction between the two occurrences of "ID".

You have multiple choices:

  • You can utilize the default JSON serializer that aligns with camel case and adjust your frontend code accordingly.
  • A slight modification: Change "ID" to "Id" in C#. This minimizes confusion since your JSON properties will now be id and unitId.
  • Add attributes like [JsonProperty] (with Json.NET) or [JsonPropertyName] (with System.Text.Json) on the C# class properties to fully control their naming in JSON.
  • You can configure the JSON serializer to avoid camel casing conversion. The JSON property names will then mirror the C# properties. The configuration method varies based on your ASP.NET Core version. Starting from ASP.NET Core 3, Json.NET was swapped out for System.Text.Json.

If you're using ASP.NET Core MVC 2.1, you can customize the Json.NET serializer in Startup.ConfigureServices:

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        // Other changes to options.SerializerSettings ...
    });

In this snippet, I'm reverting the contract resolver back to the default instead of the camel case version (

CamelCasePropertyNamesContractResolver
).

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

Using Ionic 2 to close the FAB menu with a button press

Is there a way to automatically close the FAB menu when a button inside it is pressed? Take a look at the button: <ion-fab bottom center > <button ion-fab><b>Hello</b></button> <ion-fab-list side="top"> <button ion- ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

"Investigating the impact of import quantities on the total size of an Angular production bundle

I searched for an answer but couldn't find one to address my fundamental question. I am currently constructing an Angular App and encountered a situation where I wanted to switch out the angular material components with ionic web components. However, ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Is it possible to define a multiplication margin using css?

I am trying to place a box in the center of a container, but I am unable to set a static height for the parent element as it may change. This is causing issues with aligning the box perfectly in the middle of the page. Any assistance would be greatly app ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Challenges with Type Casting in TypeScript

Upon reviewing a specific piece of code, I noticed that it is not producing any compile time or run time errors even though it should: message: string // this variable is of type string -- Line 1 <br> abc: somedatatype // lets assume abc is of some ...

The dynamic links are not supported by Webpack when used with Angular2

The Challenge I am faced with the task of creating a reusable Angular2 component that can display a custom image and be utilized by multiple other components. The goal is to have the flexibility to customize the image being displayed by passing a variable ...

Ways to alter the color of individual pseudo elements using a CSS loop

While working on creating a typewriter animation effect for my website using only CSS that I discovered through some online research, a question popped into my mind - is it possible to set different colors for each text in the animation? I have included t ...

Dynamic JSON property addition in C# at runtime

Below is an example of my JSON structure: [ { "id": "test.txt", "fields": { "_str.application": [ "Text File" ], "_str.body": [ "asdsadasd" ], "_str.mimetype": [ "text/plain" ] } } ] Is there a way to dynamically add new ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

What is the method for performing a cross-domain GET request for an XML feed within a WordPress plugin?

Is it possible to utilize AJAX in my Wordpress plugin to showcase dynamic content sourced from an XML feed on a remote domain that I do not own? I have experimented with jQuery plugins that utilize YQL for cross-domain AJAX calls, but they mainly focus on ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

Angular and Node integration with Firestore authentication

I need some guidance with integrating an Angular application and a Node.js API, both using Firestore (Firebase). We have encountered an issue when validating tokens for authenticated users - the token never seems to expire. Even after logging out in the An ...

Team members

Just started diving into Angular and practicing coding with it while following video tutorials. However, I've stumbled upon something in my code that has left me puzzled. I'm curious about the significance of the line "employees: Employee[]" in ...

What steps should I follow to utilize the POST technique effectively?

I find myself in a dilemma on the topic of "utilizing the POST method for storing data submitted through my form". Take a look at my form below: <form class="myForm"> <div class="form-group"> <label for="nameForm">Name</la ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...

What is the process for implementing a pipe to establish data binding?

I've been trying to use a pipe for data binding in Angular, but it's not working as expected. Previously, I had this: [message]="enum.text" and now I want to replace enum.text with a custom pipe. Here's what I tried: [text]=" '' ...