重點關注之自訂序列化方式(Protobuf和Msgpack)

來源:互聯網
上載者:User

標籤:

除了預設的JSON和XML序列化器外,如果想使用其它格式的(比如二進位)序列化器,也是可以的。比如著名的Protobuf和Msgpack,它們都是二進位的序列化器,特點是速度快,體積小。使用方法如下。

1.定義MediaTypeFormatter,這裡以定義MsgPack的formatter為例,主要代碼如下。

2.WebApiConfig中註冊,代碼如下。

3.用戶端調用(要求標頭中指定Accept),在.net端調用使用HttpClient,代碼如。

附:MessagePackMediaTypeFormatter原始碼。

using MsgPack;using MsgPack.Serialization;using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Formatting;using System.Net.Http.Headers;using System.Threading.Tasks;using System.Web;namespace HWA.OData.Site.Formatter{    /// <summary>    /// MsgPack序列化器formatter    /// </summary>    public class MessagePackMediaTypeFormatter : MediaTypeFormatter    {        private readonly string _mime = "application/x-msgpack";        Func<Type, bool> IsAllowedType = (t) =>        {            if (!t.IsAbstract && !t.IsInterface && t != null && !t.IsNotPublic)                return true;            if (typeof(IEnumerable).IsAssignableFrom(t))                return true;            return false;        };        public MessagePackMediaTypeFormatter()        {            SupportedMediaTypes.Add(new MediaTypeHeaderValue(_mime));        }        public override bool CanWriteType(Type type)        {            if (type == null)                throw new ArgumentNullException("Type is null");            return IsAllowedType(type);        }        public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, HttpContent content, TransportContext transportContext)        {            if (type == null)                throw new ArgumentNullException("type is null");            if (stream == null)                throw new ArgumentNullException("Write stream is null");            var tcs = new TaskCompletionSource<object>();            if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type))            {                value = (value as IEnumerable<object>).ToList();            }            var serializer = MessagePackSerializer.Create<dynamic>();            serializer.Pack(stream, value);            tcs.SetResult(null);            return tcs.Task;        }        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)        {            var tcs = new TaskCompletionSource<object>();            if (content.Headers != null && content.Headers.ContentLength == 0)                return null;            try            {                var serializer = MessagePackSerializer.Create(type);                object result;                using (var mpUnpacker = Unpacker.Create(stream))                {                    mpUnpacker.Read();                    result = serializer.UnpackFrom(mpUnpacker);                }                tcs.SetResult(result);            }            catch (Exception e)            {                if (formatterLogger == null) throw;                formatterLogger.LogError(String.Empty, e.Message);                tcs.SetResult(GetDefaultValueForType(type));            }            return tcs.Task;        }        public override bool CanReadType(Type type)        {            if (type == null)                throw new ArgumentNullException("type is null");            return IsAllowedType(type);        }    }}

重點關注之自訂序列化方式(Protobuf和Msgpack)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.