web api JSON格式化

在WebApiConfig 注册下

   GlobalConfiguration.Configuration.Formatters
            .JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                //NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, //设置忽略值为 null 的属性
                ContractResolver = new CamelCasePropertyNamesContractResolver(),        //小驼峰命名法,格式化日期时间
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            };

如果你的方法返回的是IHttpActionResult,那么还需要再基类重写一下JSON方法

 public class BaseApiController : ApiController
    {
        protected internal new JsonResult<T> Json<T>(T content)
        {
            return Json<T>(content, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings, System.Text.Encoding.UTF8);
        }
    }

 


版权声明:本文为qq_21790383原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。