3

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 } ?

haldo
  • 14,512
  • 5
  • 46
  • 52
simoro2668
  • 31
  • 1
  • 2

1 Answers1

9

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;
});
haldo
  • 14,512
  • 5
  • 46
  • 52
  • 3
    Bogus.... Docs can be confusing in that sense: default case insensitive is false as by this: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.propertynamecaseinsensitive?view=net-6.0 .... anyhow nice find. – Stefan Dec 24 '21 at 23:02
  • @Stefan while the link does say that, haldo is right and the `PropertyNameCaseInsensitive` property is `true` by default using asp.net 6. This could easily be confirmed using postman and the boilerplate Web API code. – AsPas Jun 04 '22 at 13:04
  • In my case it was `builder.Services.Configure(o => o.JsonSerializerOptions.IncludeFields = true)` – Mateusz Budzisz Feb 07 '23 at 10:24