Out of the box SignalR uses JSON to serialize/deserialize the data you send over the wire. This is great from a readability perspective and makes it easy to see the sent messages in your favorite browser dev tools. Unfortunately JSON is rather verbose which impacts performance and bandwidth usage.
But did you know that you can also use MessagePack as an alternative?
From the documentation:
MessagePack is a binary serialization format that is fast and compact. It's useful when performance and bandwidth are a concern because it creates smaller messages compared to JSON. Because it's a binary format, messages are unreadable when looking at network traces and logs unless the bytes are passed through a MessagePack parser. SignalR has built-in support for the MessagePack format, and provides APIs for the client and server to use.
Here is how to enable it:
- First you need to download the Microsoft.AspNetCore.SignalR.Protocols.MessagePack NuGet package.
- Next step is to add the MessagePack protocol to the middleware configuration:
- On your Javascript frontend you can also use Messagepack through the @microsoft/signalr-protocol-msgpack npm package:
npm install @microsoft/signalr-protocol-msgpack
- Now you can update your client configuration and activate the MessagePack protocol:
Be aware that it is not all rainbows and unicorns. Switching to MessagePack is more than changing the protocol. There are some quirks you need to be aware of before making the switch: