Fork me on GitHub
Jil序列化JSON

使用Jil序列化JSON提升Asp.net web api 性能

 

JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环。

在Asp.net web api 里面我们可以插入自定义的MediaTypeFormatter(媒体格式化器),

说白了就是根据HTTP content-type application/json

来判断采用哪种媒体格式化器

具体实现,记得要引入Jil包


 

复制代码
  public class JilFormatter : MediaTypeFormatter
        {
        private readonly Options _jilOptions;
        private MethodInfo _method;

        public JilFormatter()
            {
            //要序列化的时间格式
            _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601);
            //媒体类型
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            //加入 UTF8Encoding 编码
            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
            //加入 UnicodeEncoding 编码
            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));


            }
        //判断是否反序列化类型
        public override bool CanReadType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }
        //判断是否序列化类型
        public override bool CanWriteType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }

        //  异步反序列化一个指定类型的对象。
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
            {
            return Task.FromResult(DeserializeFromStream(type, readStream));
            }

        private object DeserializeFromStream(Type type, Stream readStream)
            {
            try
                {
                using (var reader = new StreamReader(readStream))
                    {
                    return JSON.Deserialize(reader, type, _jilOptions);
                    }
                }
            catch
                {
                return null;
                }
            }

        //  异步序列化一个指定类型的对象。
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
            {
            var streamWriter = new StreamWriter(writeStream);
            JSON.Serialize(value, streamWriter, _jilOptions);
            streamWriter.Flush();
            return Task.FromResult(writeStream);
            }
        }
复制代码

 

加入到媒体格式化器集合中

复制代码
 public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            
                );
GlobalConfiguration.Configuration.Formatters[0] = new JilFormatter(); } }
复制代码

控制类

复制代码
  public class HomeController : ApiController
        {
     public static   List<Market> Markets = new List<Market>();

        public HomeController()
            {
          
            }

         static HomeController()
            {
            Markets.Add(new Market { Id = 1, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 2, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 3, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 4, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 5, Name = "1", DateTimeNow = DateTime.Now });
            }
        public IEnumerable<Market> Get()
            {
            return Markets;
            }
        public HttpResponseMessage Post([FromBody]Market value)
            {
            Markets.Add(value);
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Put(int id, [FromBody]Market value)
            {
            var market = Markets.Where(x => x.Id == id).FirstOrDefault();
            if (market == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            market.Name = value.Name;
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Delete(int id)
            {
            var result = Markets.Remove(Markets.Where(x => x.Id == id).FirstOrDefault());
            return result
                ? new HttpResponseMessage(HttpStatusCode.Accepted)
                : new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }
复制代码

 

我们通过postman访问

我们在post一个实体

 

我们在get一下

 

已经可以看见刚才post的实体了。

源码:http://pan.baidu.com/s/1i3o6KD3

Asp.net Mvc vnext 系列  http://www.cnblogs.com/liek/p/4634294.html

得到你的肯定是我最大的动力!

 
分类: Asp.net vnext
posted on 2015-10-17 23:43  HackerVirus  阅读(2291)  评论(2编辑  收藏  举报