Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Binding case sensitivity

I created CRUD controller. When creating a model, I need to use schema:

{ "id": int, "name": string }

But the controller also binds the schema

{ "Id": int, "Name": string }

How can I force the controller bind only lowercase version { "id": int, "name": string } ?

like image 969
simoro2668 Avatar asked Oct 15 '25 11:10

simoro2668


1 Answers

The default JsonSerializerOptions values for web apps is case-insensitive.

Taken from these docs (see the note):

By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set JsonSerializerOptions.PropertyNameCaseInsensitive to true:

Note

The web default is case-insensitive.

You want to configure the serializer to use PropertyNameCaseInsensitive = false in order to be case-sensitive.

You can configure the options in ConfigureServices method in Startup.cs:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
    });

or in .NET 6 using minimal API:

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
});
like image 88
haldo Avatar answered Oct 17 '25 23:10

haldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!