博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebApi 返回小驼峰式 json 格式,并格式化日期
阅读量:7046 次
发布时间:2019-06-28

本文共 1327 字,大约阅读时间需要 4 分钟。

from:http://blog.csdn.net/magiccops/article/details/42969363

 

  屏蔽默认返回xml格式:Global文件加:GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

 

 

在 WebApiConfig 类中增加方法ConfigureApi,并在 Register 方法最后调用一下    ConfigureApi(config);    

增加一个实现IContentNegotiator 接口的类 JsonContentNegotiator

详细如下:

 public static void ConfigureApi(HttpConfiguration config)

        {

            var jsonFormatter = new JsonMediaTypeFormatter();

            var settings = jsonFormatter.SerializerSettings;


            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();

            //这里使用自定义日期格式

            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

            settings.Converters.Add(timeConverter);



            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));   

        }

  public class JsonContentNegotiator : IContentNegotiator

    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;
        public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
        {
            _jsonFormatter = formatter;
        }
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
            return result;
        }
    }

 

转载于:https://www.cnblogs.com/94cool/p/4386440.html

你可能感兴趣的文章
【Django笔记二】Django2.0配置模板和静态文件
查看>>
jsonp
查看>>
元素的属性及分析
查看>>
Ajax中location.href无法跳转的解决办法
查看>>
fedora23没有/var/log/messages &如何禁用后台自动更新软件?
查看>>
Linux基础_软链接,硬链接
查看>>
Java-枚举类,注解
查看>>
MySQL 的Coalesce函数
查看>>
SQL 无法连接服务器
查看>>
我的项目管理之干系人分析在单位项目中的运用
查看>>
About Spring MVC
查看>>
Vijos 1067Warcraft III 守望者的烦恼
查看>>
java servlet 几种页面跳转的方法及传值
查看>>
集群、分布式、负载均衡区别
查看>>
Java Timer定时器时,每次重复执行了两次任务的解决方案
查看>>
欧几里得算法与扩展欧几里得算法
查看>>
Spring远程服务(RPC)
查看>>
ACM-ICPC 2018 徐州赛区网络预赛A Hard to prepare(DP)题解
查看>>
Linux问题:Crontab 执行shell脚本时相对路径的问题,不能识别。
查看>>
用户注册的邮箱激活模块的设计与实现
查看>>