我正在通过ASP.NET Core / Web API / Angular 2上的WintellectNOW课程进行学习。我已经实现了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")]只是为了确定装饰属性而已,仍然没有关系。
[DataMember(Name = "Id")]
在偶然的机会上,它与控制器中的Action和instance变量有关。
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中,默认情况下(根据此声明)驼峰式存储JSON属性。
您可以通过替换来禁用此功能
services.AddMvc();
与
services .AddMvc() .AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver());
在您的Startup.cs文件中。您必须将其添加using Newtonsoft.Json.Serialization;到文件的顶部。
using Newtonsoft.Json.Serialization;
随着DefaultContractResolver到位,属性名称将在JSON输出表示一字不差。不需要DataMember属性。
DefaultContractResolver
DataMember