Using MessagePack with ASP.NET Core WebAPI

September 12, 2018 by Anuraj

ASPNET Core MessagePack

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.

ASP.NET Core MessagePack Formatter

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.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(option =>
    {
        option.OutputFormatters.Clear();
        option.OutputFormatters.Add(new MessagePackOutputFormatter(ContractlessStandardResolver.Instance));
        option.InputFormatters.Clear();
        option.InputFormatters.Add(new MessagePackInputFormatter(ContractlessStandardResolver.Instance));
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Now if you run your app, you will be able to see the values in MessagePack format, not in JSON format.

ASP.NET Core MessagePack Output

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.

var oReq = new XMLHttpRequest();
oReq.open("GET", "/api/values", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
    var arrayBuffer = oReq.response;
    if (arrayBuffer) {
        var byteArray = new Uint8Array(arrayBuffer);
        var obj = deserializeMsgPack(byteArray);
        $("#textResponse").val(JSON.stringify(obj));
    }
};

oReq.send(null);

And here is the method to POST data.

var xhttp = new XMLHttpRequest();
var data = "Hello World";
xhttp.open("POST", "/api/values", true);
var bytes = serializeMsgPack(data);
xhttp.send(bytes);

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.

$.ajax({
    url: "/api/values",
    dataType: "arraybuffer",
    method: 'GET'
}).done(function (response) {
    var byteArray = new Uint8Array(response);
    var obj = deserializeMsgPack(byteArray);
    console.log(JSON.stringify(obj));
});

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.

var bytes = serializeMsgPack(person);
$.ajax({
    url: "/api/values",
    dataType: "arraybuffer",
    method: 'POST',
    data: bytes
}).done(function (response) {
    console.log('Done');
});

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.

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("https://localhost:44362/");
    var result = httpClient.GetAsync("api/values").Result;
    var bytes = result.Content.ReadAsByteArrayAsync().Result;
    var data = MessagePackSerializer.Deserialize<IEnumerable<string>>(bytes);
}

And here is the POST method, which will send the data as bytes using C#.

var data = "Hello World";
using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("https://localhost:44362/");
    var buffer = MessagePackSerializer.Serialize(data);
    var byteContent = new ByteArrayContent(buffer);
    var result = httpClient.PostAsync("api/values", byteContent).Result;
}

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub