从ASP .Net Core 1.0.0-rc2-final到1.0.0的交换,JSON属性现在小写

时间:2016-07-05 11:15:00

标签: asp.net-core asp.net-core-1.0

我刚刚将我们的项目从ASP .Net Core 1.0.0-rc2-final交换到1.0.0。由于JSON属性的大写,我们的网站和客户端已停止工作。例如,这一行JavaScript现在失败了

for (var i = 0; i < collection.Items.length; i++){

因为控制器现在调用数组&#34; items&#34;而不是&#34; Items&#34;。除了安装更新的软件包和编辑project.json文件之外,我没有做任何更改。我还没有更改仍然大写其属性的C#模型文件。

为什么ASP.Net核心控制器开始返回具有较低属性的JSON?我如何回过头来表达模型中属性名称的情况呢?

8 个答案:

答案 0 :(得分:106)

MVC现在默认使用驼峰案例名称序列化JSON

默认情况下,使用此代码可以避免使用驼峰名称

  services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

来源: https://github.com/aspnet/Announcements/issues/194

答案 1 :(得分:12)

如果您是从Google找到的,并正在寻找Core 3的解决方案。

Core 3使用System.Text.Json,默认情况下不会保留大小写。如对此Github issue所述,将PropertyNamingPolicy设置为null将解决此问题。

public void ConfigureServices(IServiceCollection services)
{
...
    services.AddControllers()
            .AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);

答案 2 :(得分:11)

您可以更改此行为:

services
    .AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

请参阅此处的公告:https://github.com/aspnet/Announcements/issues/194

答案 3 :(得分:9)

对于那些迁移到Core 3.1并拥有Core MVC项目的用户,可以在Startup.cs中使用以下设置代码:


        public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
            ...
        }

答案 4 :(得分:1)

这将在dotnet core 3 webapi中对其进行修复,以使其完全不更改您的属性名称,并且您将完全按照自己的意图返回给客户端。

在Startup.cs中:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
        services.AddHttpClient();
    }

答案 5 :(得分:0)

对于某些使用ASP.net WEB API(而不是ASP.NET Core)的人。

将此行添加到WebApiConfig中。

//Comment this jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

在这里添加答案作为答案,因为这也是Google搜索网络api中首先出现的问题。

答案 6 :(得分:0)

对于Core 2.x版本,使用此代码可以默认避免使用驼峰式案例名称。您需要在Startup.cs文件的ConfigureServices方法内添加以下代码。

services.AddMvc()
.AddJsonOptions(o =>
{
    if (o.SerializerSettings.ContractResolver != null)
    {
        var castedResolver = o.SerializerSettings.ContractResolver
        as DefaultContractResolver;

        castedResolver.NamingStrategy = null;
    }
});

答案 7 :(得分:0)

对于不想全局设置的人,也可以使用ContractResolver作为Json结果返回:

public IActionResult MyMethod()
{
    var obj = new {myValue = 1};
    return Json(obj, new JsonSerializerSettings {ContractResolver = new DefaultContractResolver()});
}
相关问题