JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0

前提是你 提交于 2019-11-27 12:37:56

问题


I've just swapped our project from ASP .Net Core 1.0.0-rc2-final to 1.0.0. Our website and client have stopped working because of the capitalization of JSON properties. For example, this line of JavaScript now fails

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

because the controller now calls the array "items" instead of "Items". I have made no changes beyond installing the updated packages and editing the project.json file. I have not changed the C# model files which still capitalize their properties.

Why have the ASP.Net Core controllers started returning JSON with lower-cased properties? How do I go back to them honoring the case of the property names from the model?


回答1:


MVC now serializes JSON with camel case names by default

Use this code to avoid camel case names by default

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

Source: https://github.com/aspnet/Announcements/issues/194




回答2:


You can change the behavior like this:

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

See the announcement here: https://github.com/aspnet/Announcements/issues/194




回答3:


In case you found this from Google and looking for a solution for Core 3.

Core 3 uses System.Text.Json, which by default does not preserve the case. As mentioned with this Github issue, setting the PropertyNamingPolicy to null will fix the problem.

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



回答4:


For some one who is using ASP.net WEB API ( rather than ASP.NET Core).

Add this line in your WebApiConfig.

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

jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

Adding this as an answer here because this comes up first in google search for web api as well.




回答5:


This will fix it in dotnet core 3 webapi, so that it doesn't change your property names at all, and you return to your client exactly what you intended to.

In Startup.cs:

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


来源:https://stackoverflow.com/questions/38202039/json-properties-now-lower-case-on-swap-from-asp-net-core-1-0-0-rc2-final-to-1-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!