c# - ASP.NET Core 绑定(bind)区分大小写

标签 c# asp.net-core asp.net-web-api binding

我创建了 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.csConfigureServices 方法中配置选项:

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/

相关文章:

c# - 如何在 C# 中用 '#' 拆分字符串

c# - Asp net Core ConfirmEmail 不工作

javascript - 在客户端机器上执行webapi函数(访问客户端系统的数据库)

c# - .NET Core EF 2.1 脚手架-数据库优先-如何添加更多表

asp.net-core - Asp.net 核心 5 Odata 错误(services.AddOData;不工作)

asp.net - 使用 ETW 捕获传入 HTTP 请求和传出 HTTP 请求

c# - Visual Studio 2017 Collapsing 还删除了未使用的使用

c# - 为什么负枚举成员最后被 foreach 枚举?

C# 相当于 file_get_contents (PHP)

asp.net-core - 向 ASP.NET Core Web API 服务发送 "application/octet-stream"时发布请求错误