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

后端 未结 8 1995
逝去的感伤
逝去的感伤 2020-12-08 12:54

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

相关标签:
8条回答
  • 2020-12-08 13:41

    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

    0 讨论(0)
  • 2020-12-08 13:43

    For someone who does not want to set it globally, it is possible to use ContractResolver also to return as Json result:

    public IActionResult MyMethod()
    {
        var obj = new {myValue = 1};
        return Json(obj, new JsonSerializerSettings {ContractResolver = new DefaultContractResolver()});
    }
    
    0 讨论(0)
  • 2020-12-08 13:45

    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

    0 讨论(0)
  • 2020-12-08 13:47

    For those who migrated to Core 3.1 and have Core MVC project can use following setup code in Startup.cs:


            public void ConfigureServices(IServiceCollection services)
            {
                ...
                services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
                ...
            }
    
    0 讨论(0)
  • 2020-12-08 13:50

    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);
    

    and if you don't want to change the global settings, for one action only it's like this:

    return Json(obj, new JsonSerializerOptions { PropertyNamingPolicy = null });
    
    0 讨论(0)
  • 2020-12-08 13:51

    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.

    0 讨论(0)
提交回复
热议问题