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

Is there a way to loop through objects in Angular 2

I am working with an Array of Objects named comments, and my goal is to select only the ones that have a specific post id and copy them to another array of objects. The issue I am facing is finding a way to duplicate the object once it has been identified. ...

What is the process for extracting a list of objects from a JSON String that contains various reference units, using a mapper function?

My goal is to extract all selected columns and store them in the database as a Json String. Then, I need to convert them back into a List of Objects and send them back to the UI. The structure of my Json data is shown below. I am specifically looking to ...

The results do not appear when using Bootstrap 3 Typeahead

I am currently utilizing Bootstrap 3 Typeahead in conjunction with an ajax call. The function is successfully returning the data, however, it is not displaying. Below is my code snippet: $('#txtComune').typeahead({ minLength: 2, ...

Angular 2 Index HTML loading process for text display

I am a beginner with angular 2. While exploring an angular 2 project created using angular-cli, I came across the following code in the index.html file. However, it seems that the word "Loading" is not being displayed. <app-root>Loading ...</app- ...

Unable to display parsed JSON data on Android device

I'm having trouble displaying a JSON string generated by a PHP file on an Android TextView. Can anyone help me figure out why? public class AllUsersActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

ag-grid Server Side pagination function to enable independent setting of last row

Currently, I am utilizing ag-grid, Angular 7, and implementing a server-side datasource with pagination. In my API setup, I initiate two requests: the first request provides the total number of items in the table, while the second fetches the data for the ...

Angular 2 Issue: Unable to connect to 'routerlink' because it is not recognized as a valid property of 'a' tag

As a newcomer to Angular 2, I am attempting to create a sample application based on a Pluralsight tutorial. However, I encountered the mentioned error when trying to set up Routes. I am struggling to identify the cause of this error. Any assistance would ...

Changing the size of a div component using Angular 6

Currently, I am working on implementing Angular's element resize feature. I am utilizing this library: https://github.com/mattlewis92/angular-resizable-element Here is my custom module: import { ResizableModule } from 'angular-resizable-elemen ...

The Angular application is unable to find any matching routes while operating on a secure HTTPS

I am facing an issue with my Angular application created using the Radzen IDE and hosted on IIS. There is an anchor tag in the application that links to a .Net API for downloading files. The href of the anchor tag is structured like this: https://[Angular ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Converting a JSON image URL string into a Bitmap image for displaying images in an Android application

I'm currently working on an Android app where I need to retrieve images from a server database. I used JSON to fetch the images stored in folders on the file system, but when I try to access the getImages.php link in my app, the images don't disp ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

The unexpected error occurs when using JSON.parse() with the message 'Unexpected end of JSON input'

The output produced by console.log(d) is in hexadecimal code: <Buffer 7b 22 73 75 63 63 65 73 73 22 3a 74 72 75 65 2c 22 64 61 74 61 22 3a 7b 22 73 75 6d 6d 61 72 79 22 3a 7b 22 74 6f 74 61 6c 22 3a 31 39 39 32 35 36 30 ... 293 more bytes> <Buff ...

Changing {number, Observable<string>} to Observable<number, string> is a necessary transformation to be made

Is there a way to convert an array of objects with the following structure: { id: number, data: Observable<string> } into an array of objects with this structure: Observable<{id: number, data: string}> using only RxJS operators? ...

Searching with Mat-autocomplete across multiple fields simultaneously

I am struggling with a mat-autocomplete that contains 5000 objects, each consisting of a first name and a last name. My goal is to search for both the first name and last name simultaneously regardless of the input order. Currently, I can only search one ...

Is it possible to modify the div id using C# code behind?

I have a division that looks like this: <div id="divAdditionalInfo" runat="server"> //html code here </div> In the back-end code, I want to display a small window (generated by this div) more than once. However, since it's the same div, ...

When Utilizing an async Task Method, DbContext is Properly Disposed

Currently, I have set up an async Task method to handle the IAuthenticationFilter interface. After logging in successfully, I can access an API with no issues when it has this attribute. However, if I revisit the API later on, an exception is thrown. publ ...