Using MsgPack in your asp.net core webapi



MsgPack (here) is reportedly faster then msgpack-cli in terms of performance. To get your excited, check out the diagram below :-


Yes, it is ridiculously fast and beat protobuf in many ways. I was gonna put on my hardworking cap and write up some formatters but this way is easier to do :-


Client code 

Client side code to de-serialized it.

using MessagePack;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Alphacert.Acc.Ods.Client
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var client = new HttpClient
{
BaseAddress = new Uri("http://localhost:5050")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/x-msgpack"));
var result = await client.GetAsync("/ODSData/valuationsdata?version=1&last-modified=1");
var bytes = await result.Content.ReadAsByteArrayAsync();
var returnValueType = MessagePackSerializer.Deserialize<ViewValuation>(bytes);
Console.WriteLine(returnValueType.GetType().Name);
Console.WriteLine(returnValueType?.PortfolioId);
}
}
}



Install

Install it through nuget using the following command :-

Install-Package WebApiContrib.Core.Formatter.MessagePack -Version 2.0.0


Next, you gotta decorate your objects with the correct attributes.

[MessagePackObject]
public class ViewValuation
{
[Key(0)]
public string InstrumentId { get; set; }
[Key(1)]
public string FundKey { get; set; }
[Key(2)]
public string PortfolioId { get; set; }
[Key(3)]
public decimal? GrossMarketValueBase { get; set; }
[Key(4)]
public DateTime ModifiedAt { get; set; }
}



And then somewhere in your controller, you can serialize your object as bytes and push it through using code below :-

var path = Path.Combine(AppConstant.fileResourceFolder, AppConstant.fileResourceName);
if (System.IO.File.Exists(path))
{
var result = MessagePackSerializer.Serialize(new ViewValuation() { PortfolioId = "00000" });
return File(result, "application/x-msgpack");
}
else
{
return Accepted(); //not ready
}

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20