gpt4 book ai didi

c# - 如何在 JSON 响应 ASP.NET Core 中关闭或处理 camelCasing?

转载 作者:太空狗 更新时间:2023-10-29 20:09:36 25 4
gpt4 key购买 nike

我正在学习有关 ASP.NET Core/Web API/Angular 2 的 WintellectNOW 类(class)。我已经实现了 API 部分,但无论出于何种原因,返回的 JSON 的变量名称都被小写了。

返回的 JSON 格式如下...

[
{"id":1,"name":"Bowler","color":"black","count":1},
{"id":2,"name":"Fedora","color":"red","count":1},
{"id":3,"name":"Baseball Cap","color":"blue","count":3}
]

我期待...

[
{"Id":1,"Name":"Bowler","Color":"black","Count":1},
{"Id":2,"Name":"Fedora","Color":"red","Count":1},
{"Id":3,"Name":"Baseball Cap","Color":"blue","Count":3}
]

基于...的C#模型

namespace HatCollection.Models
{
public class Hat
{
public int Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public int Count { get; set; }
}
}

我什至用 [DataMember(Name = "Id")] 装饰属性只是为了确保它仍然没有关系。

偶有与 Controller 中的Action和实例变量有关...

private static readonly List<Hat> MyHats = new List<Hat>
{
new Hat {Id = 1, Name = "Bowler", Color = "black", Count = 1 },
new Hat {Id = 2, Name = "Fedora", Color = "red", Count = 1 },
new Hat {Id = 3, Name = "Baseball Cap", Color = "blue", Count = 3 }
};

[HttpGet]
public IEnumerable<Hat> Get()
{
return MyHats;
}

如何关闭 camelCase 功能,以便 ASP.NET Core 返回属性名称而不更改它们?

最佳答案

在 Asp.Net Core 3.0 中,有些事情发生了变化。对于 camelCase,不做任何开箱即用的事情。对于 PascalCase 或其他集合样式使用。

services.AddMvc(setupAction=> {
setupAction.EnableEndpointRouting = false;
}).AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

在 Startup.cs ConfigureServices 部分

关于c# - 如何在 JSON 响应 ASP.NET Core 中关闭或处理 camelCasing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728200/

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