How to turn off or handle camelCasing in JSON response ASP.NET Core?

后端 未结 7 1721
攒了一身酷
攒了一身酷 2020-11-29 07:55

I\'m running through a WintellectNOW course on ASP.NET Core/Web API/Angular 2. I have the API portion implemented, but for whatever reason, the JSON that is being returned h

7条回答
  •  一个人的身影
    2020-11-29 08:42

    You have to change the DefaultContractResolver which uses camelCase by default. Just set the NamingStatergy as null.

    This should be done in the StartUp.ConfirgureService as follows.

      public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddMvcOptions(o => o.OutputFormatters.Add(
                    new XmlDataContractSerializerOutputFormatter()));
    
                .AddJsonOptions(o => {
                    if (o.SerializerSettings.ContractResolver != null)
                    {
                        var castedResolver = o.SerializerSettings.ContractResolver
                            as DefaultContractResolver;
                        castedResolver.NamingStrategy = null;
                    }
                });
        }
    

    Option 2

    Use JSonProperty as follows.

    public class Hat
    {
        [JsonProperty("id")]
        public int Id { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("color")]
        public string Color { get; set; }
        [JsonProperty("count")]
        public int Count { get; set; }
    }
    

提交回复
热议问题