標籤:
除了預設的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)