How to add CamelCasePropertyNamesContractResolver in Startup.cs?

前端 未结 3 824
慢半拍i
慢半拍i 2020-12-14 17:13

Here is my Configure method from my Startup class.

public void Configure(IApplicationBuilder app)
{
    // Setup configuration sour         


        
相关标签:
3条回答
  • 2020-12-14 17:26

    Use below setting to avoid lowercase replacement for .net core services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

    0 讨论(0)
  • 2020-12-14 17:33

    The Configure function was removed from services.AddMvc() in either Beta 6 or 7. For Beta 7, in Startup.cs, add the following to the ConfigureServices function:

    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver = 
            new CamelCasePropertyNamesContractResolver();
    });
    
    0 讨论(0)
  • 2020-12-14 17:34

    Replace services.AddMvc(); with the following.

    services.AddMvc().SetupOptions<MvcOptions>(options =>
    {
        int position = options.OutputFormatters.FindIndex(f => 
                                        f.Instance is JsonOutputFormatter);
    
        var settings = new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        var formatter = new JsonOutputFormatter(settings, false);
    
        options.OutputFormatters.Insert(position, formatter);
    });
    

    UPDATE

    With the current version of ASP.NET, this should do.

    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.OutputFormatters
                   .Where(f => f.Instance is JsonOutputFormatter)
                   .Select(f => f.Instance as JsonOutputFormatter)
                   .First()
                   .SerializerSettings
                   .ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    UPDATE 2

    With ASP.NET 5 beta5, which is shipped with Visual Studio 2015 RTM, the following code works

    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.OutputFormatters.OfType<JsonOutputFormatter>()
               .First()
               .SerializerSettings
               .ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    UPDATE 3

    With ASP.NET 5 beta7, the following code works

    services.AddMvc().AddJsonOptions(opt =>
    {
        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    RC2 UPDATE

    MVC now serializes JSON with camel case names by default. See this announcement. https://github.com/aspnet/Announcements/issues/194

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