gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:54:53 33 4
gpt4 key购买 nike

我创建了 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 namematches between JSON and the target object properties. To change thatbehavior, set JsonSerializerOptions.PropertyNameCaseInsensitive totrue:

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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com