September 12, 2018 by Anuraj Estimated read time : 5 mins
This post is about how to use MessagePack in ASP.NET Core and C#. MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it’s faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.
First you need to install MessagePack.AspNetCoreMvcFormatter package.
This will help you to configure your input and output request as MessagePack. Next you can modify ConfigureServices method to support input and output requests.
Now if you run your app, you will be able to see the values in MessagePack format, not in JSON format.
You can consume the data using XMLHttpRequest using following code. You require msgpack.js for this purpose, it will help you to deserialize data from server.
And here is the method to POST data.
To consume the response from the server side using JQuery, you need another script library - jquery-ajax-blob-arraybuffer.js, this is required because JQuery Ajax doesn’t support arrayBuffer datatype.
Here is the get method which sends a GET request and display the data.
The jquery-ajax-blob-arraybuffer.js is helps you to send the request with arraybuffer datatype. And msgpack.js required to deserialize the binary data to JSON. Similarly here is the POST method, which helps to send the data in MessagePack format.
This will convert the data from browser to MessagePack format and send it to server and ASP.NET Core can process it.
You can use MessagePack nuget package for consuming MessagePack in C# client apps. Here is the GET request with HttpClient. Since I am using a console application, I am not using async methods, instead I am using result property.
And here is the POST method, which will send the data as bytes using C#.