asp.net core 1.0 web api use camelcase

依然范特西╮ 提交于 2019-11-26 15:44:51

问题


On RC2 the same code returns json format with camel case. After netcore 1.0 release i started new project and the same code is returning json in lowercase.

Tried multiple solutions but none of them were working web-api-serialize-properties-starting-from-lowercase-letter


回答1:


services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });

This keeps a JSON object's name the same as .NET class property.




回答2:


You can configure JSON behavior this way:

public void ConfigureServices(IServiceCollection services)  
  {
      services.AddMvc()
                  .AddJsonOptions(options =>
                  {
                      options.SerializerSettings.ContractResolver =
                          new CamelCasePropertyNamesContractResolver();
                  });
  }



回答3:


You can also do this at the individual serializer level, instead of at the global level.

For example, to return an object as JSON on a controller action method you can do this:

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() };

return new JsonResult(myObject, jsonSerializerSettings);

And the resulting JSON string will be in the expected PascalCase to match the .NET class/properties names



来源:https://stackoverflow.com/questions/38139607/asp-net-core-1-0-web-api-use-camelcase

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