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 }
?
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With