In addition to the default JSON and XML serializers, it is possible to use other formats (such as binary) serializers. such as the famous Protobuf and Msgpack, they are binary serializers, characterized by fast speed, small size. Use the following method.
1. Define Mediatypeformatter, here to define the Msgpack formatter as an example, the main code is as follows.
Registered in 2.WebApiConfig, the code is as follows.
3. Client calls (Specify accept in the request header), call using HttpClient on the. NET side, code such as.
Attached: Messagepackmediatypeformatter source code.
usingMsgpack;usingmsgpack.serialization;usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Net.Http.Formatting;usingSystem.Net.Http.Headers;usingSystem.Threading.Tasks;usingsystem.web;namespaceHWA. odata.site.formatter{/// <summary> ///Msgpack Serializer Formatter/// </summary> Public classMessagepackmediatypeformatter: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; }; PublicMessagepackmediatypeformatter () {Supportedmediatypes.add (NewMediatypeheadervalue (_mime)); } Public Override BOOLcanwritetype (Type type) {if(Type = =NULL) Throw NewArgumentNullException ("Type is null"); returnIsallowedtype (type); } Public OverrideTask writetostreamasync (Type type,Objectvalue, System.IO.Stream Stream, httpcontent content, TransportContext transportcontext) { if(Type = =NULL) Throw NewArgumentNullException ("type is null"); if(Stream = =NULL) Throw NewArgumentNullException ("Write stream is null"); varTCS =Newtaskcompletionsource<Object>(); if(Type! =typeof(string) &&typeof(IEnumerable). IsAssignableFrom (type)) {value= (value asienumerable<Object>). ToList (); } varSerializer = messagepackserializer.create<dynamic>(); Serializer. Pack (stream, value); Tcs. Setresult (NULL); returnTCS. Task; } Public Overridetask<Object>readfromstreamasync (type type, stream stream, httpcontent content, Iformatterlogger Formatterlogger) { varTCS =Newtaskcompletionsource<Object>(); if(content. Headers! =NULL&& content. Headers.contentlength = =0) return NULL; Try { varSerializer =messagepackserializer.create (type); Objectresult; using(varMpunpacker =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)); } returnTCS. Task; } Public Override BOOLcanreadtype (Type type) {if(Type = =NULL) Throw NewArgumentNullException ("type is null"); returnIsallowedtype (type); } }}
Focus on custom serialization methods (Protobuf and Msgpack)