ASP.NET Core 绑定区分大小写

sim*_*668 3 c# binding asp.net-web-api asp.net-core

我创建了 CRUD 控制器。创建模型时,我需要使用架构:

{ "id": int, "name": string }
Run Code Online (Sandbox Code Playgroud)

但控制器也绑定了模式

{ "Id": int, "Name": string }
Run Code Online (Sandbox Code Playgroud)

如何强制控制器仅绑定小写版本{ "id": int, "name": string }

hal*_*ldo 10

Web 应用程序JsonSerializerOptions的默认值不区分大小写

摘自这些文档(请参阅注释):

默认情况下,反序列化会在 JSON 和目标对象属性之间查找区分大小写的属性名称匹配。要更改该行为,请将 JsonSerializerOptions.PropertyNameCaseInsensitive 设置为 true:

笔记

Web 默认不区分大小写

您需要配置要使用的序列化器PropertyNameCaseInsensitive = false以区分大小写。

ConfigureServices您可以在方法中配置选项Startup.cs

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
    });
Run Code Online (Sandbox Code Playgroud)

或者在 .NET 6 中使用最少的 API:

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
});
Run Code Online (Sandbox Code Playgroud)

  • 虚假......从这个意义上说,文档可能会令人困惑:默认不区分大小写是错误的,如下所示:https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.propertynamecaseinsensitive? view=net-6.0 ....无论如何,很好的发现。 (3认同)