.net core返回json首字母小写的问题解决

在写.net core项目时发现后台返回的json数据的首字母都是小写,然而我定义的却是大写。原来.net core使用Newtonsoft.Json时采用驼峰样式的key。要想改为我们想要的效果那就不使用默认的驼峰式命名。有两种方式。一种是返回数据时进行设置,另一种是全局设置

 一.返回数据时设置

     [HttpPost]
        public ActionResult GetData(int? id)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            //EF Core中默认为驼峰样式序列化处理key
            //settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            //使用默认方式,不更改元数据的key的大小写
            settings.ContractResolver = new DefaultContractResolver();
            return Json(bll.GetData(id),settings);
        }

二.全局设置

  在Startup文件中进行配置

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<HomeBll>();
            services.AddTransient<ProductBll>();
            //全局配置Json序列化处理
            services.AddMvc().AddNewtonsoftJson(options =>
            {
            //忽略循环引用
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //不使用驼峰样式的key
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            //设置时间格式
            options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
             });
        }

猜你喜欢

转载自www.cnblogs.com/HTLucky/p/13194830.html
今日推荐