我创建了 CRUD Controller 。创建模型时,我需要使用模式:
{ "id": int, "name": string }
但是 Controller 也绑定(bind)了schema
{ "Id": int, "Name": string }
如何强制 Controller 只绑定(bind)小写版本 { "id": int, "name": string }
?
最佳答案
网络应用的默认 JsonSerializerOptions
值不区分大小写。
取自these docs (见注释):
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.
您想将序列化器配置为使用 PropertyNameCaseInsensitive = false
以区分大小写。
您可以在 Startup.cs
的 ConfigureServices
方法中配置选项:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});
或在 .NET 6 中使用最少的 API:
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.PropertyNameCaseInsensitive = false;
});
关于c# - ASP.NET Core 绑定(bind)区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70475942/