skip to content

How do you switch a SignalR app and its JavaScript and .NET clients to the MessagePack hub protocol, and what changes for the JavaScript client?

level: middleimportance: nice to knowfreq 26%

answer

  1. binary instead of JSON text
  2. Microsoft.AspNetCore.SignalR.Protocols.MessagePack
  3. AddMessagePackProtocol on both builders
  4. @microsoft/signalr-protocol-msgpack, withHubProtocol
  5. property names are case-sensitive

basics

~10 s

Add the Microsoft.AspNetCore.SignalR.Protocols.MessagePack package and call AddSignalR().AddMessagePackProtocol(); .NET clients call AddMessagePackProtocol() on HubConnectionBuilder, JavaScript clients add @microsoft/signalr-protocol-msgpack and withHubProtocol(new MessagePackHubProtocol()). Messages get smaller, but property names become case-sensitive.

solid answer

~40 s

JSON is the default and always registered. For MessagePack, the server references `Microsoft.AspNetCore.SignalR.Protocols.MessagePack` and calls `builder.Services.AddSignalR().AddMessagePackProtocol()`, optionally configuring `SerializerOptions`; the hub then accepts both protocols, each client choosing in the handshake. The .NET client references the same package and calls `.AddMessagePackProtocol()` on `HubConnectionBuilder`. The browser adds the npm package `@microsoft/signalr-protocol-msgpack` and `.withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())`. What changes for JavaScript: MessagePack is case-sensitive, so objects sent from JavaScript must use the C# PascalCase property names unless `[Key]` attributes rename them; `DateTime.Kind` is not preserved, so send UTC; and the protocol is binary, which rules out the Server-Sent Events transport. It also does not work under SignalR's Native AOT support, which is JSON-only.

code

javascript · 15 lines
javascript
import * as signalR from "@microsoft/signalr";
import { MessagePackHubProtocol } from "@microsoft/signalr-protocol-msgpack";

const connection = new signalR.HubConnectionBuilder()
  .withUrl("/ticker")
  .withHubProtocol(new MessagePackHubProtocol())
  .build();

// MessagePack is case-sensitive: use the C# property names.
connection.on("PriceChanged", (quote) => {
  render(quote.Symbol, quote.LastPrice);
});

await connection.start();
await connection.invoke("SetAlert", { Symbol: "MSFT", Threshold: 450 });

go deeper

for a junior

Know that SignalR uses JSON by default and can switch to the binary MessagePack protocol with an extra package on each side.

for a middle

Name the packages and calls for the server, the .NET client and the JavaScript client, and the case-sensitivity and date caveats.

for a senior

Weigh the bandwidth win against the transport limit, the Native AOT gap, harder debugging and casing changes in existing JavaScript.

for a principal

Decide per hub, from measured message volume, whether a binary protocol earns its operational cost, and make the choice explicit with SupportedProtocols.

## Why switch SignalR serializes hub messages with a **hub protocol**. The default, always registered by `AddSignalR`, is JSON via System.Text.Json, with camelCase property names. **MessagePack** is a binary format: messages are smaller and faster to serialize, which matters for a stock ticker pushing many small price updates a second to thousands of screens. ## Server ```csharp // Package: Microsoft.AspNetCore.SignalR.Protocols.MessagePack builder.Services.AddSignalR() .AddMessagePackProtocol(); ``` - `AddMessagePackProtocol` has an overload taking `Action<MessagePackHubProtocolOptions>`, whose `SerializerOptions` configures the MessagePack-CSharp serializer (resolvers, security settings). - JSON stays registered. With both installed, the hub accepts either, and each client names its protocol in the handshake. `HubOptions.SupportedProtocols` (default: all installed) can restrict a hub to a subset. ## .NET client The kiosk app references the same package and calls the same-named extension on the client builder: ```csharp var connection = new HubConnectionBuilder() .WithUrl("https://ticker.example.com/ticker") .AddMessagePackProtocol() .Build(); ``` ## JavaScript client The browser needs a second npm package, **`@microsoft/signalr-protocol-msgpack`**, which depends on `@microsoft/signalr`: ```javascript const connection = new signalR.HubConnectionBuilder() .withUrl("/ticker") .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) .build(); ``` With a bundler, import `MessagePackHubProtocol` from the package and pass `new MessagePackHubProtocol()`. ## What changes for JavaScript code | Concern | JSON protocol | MessagePack protocol | |---|---|---| | property names from .NET | camelCase (`lastPrice`) | as declared (`LastPrice`) | | object sent from JavaScript | camelCase binds | must match C# names exactly, or use `[Key]` | | `DateTime.Kind` | carried in the ISO 8601 string | not preserved; `Local` becomes UTC, others pass as-is | | transport | WebSockets, SSE, long polling | binary only: WebSockets or long polling | | Native AOT server (.NET 9+) | supported with the source generator | not supported | In detail: 1. **Case sensitivity.** The docs' example: for a C# `ChatMessage` with `Sender` and `Message`, the JavaScript client must send `{ Sender: "...", Message: "..." }`; camelCase names will not bind. A `[Key("sender")]` attribute from MessagePack-CSharp maps a different name. 2. **Dates.** MessagePack has no slot for `DateTime.Kind`, so convert to UTC before sending and back to local time on display. 3. **Transport.** Server-Sent Events carry text only, so a binary protocol cannot use them; a client that falls back from WebSockets goes to long polling. 4. **Debugging.** Frames in browser dev tools are binary, so reading traffic needs a decoder; trace-level client logging helps. ## When not to bother - Low-traffic hubs, where JSON's size is irrelevant and readable frames help debugging. - Native AOT servers, where SignalR's AOT support covers the JSON protocol only. - Payloads that are mostly long strings, which MessagePack barely shrinks. For the ticker, a reasonable path is to measure: switch the high-volume `PriceChanged` hub to MessagePack, keep JSON for the admin hub, and let `SupportedProtocols` make each hub's choice explicit.

  • After switching to MessagePack, the dashboard shows undefined for quote.lastPrice. Why?
    With JSON, SignalR's System.Text.Json settings camelCase .NET property names, so `lastPrice` worked. MessagePack keeps the names as declared, so the field arrives as `LastPrice`. Either read `quote.LastPrice` or put MessagePack `[Key("lastPrice")]` attributes on the C# type.
  • Can JSON and MessagePack clients connect to the same hub at once?
    Yes. `AddMessagePackProtocol` adds a protocol alongside JSON; each client names its protocol in the handshake and the hub serializes per connection. `HubOptions.SupportedProtocols`, which defaults to every installed protocol, can limit a particular hub to one.

  • Adding AddMessagePackProtocol on the server switches every existing JSON client to MessagePack.
  • The JavaScript client supports MessagePack without an extra npm package.
  • MessagePack camelCases property names just like the JSON protocol.
  • MessagePack works over every transport, including Server-Sent Events.
  • MessagePack is the protocol to pick for a Native AOT SignalR server.