Focus on custom serialization methods (Protobuf and Msgpack)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.