Vikhyath Maiya
Vikhyath Maiya

Reputation: 3202

Microsoft.AspNetCore.SignalR.Client - Enable Response compression

I am developing a application which uses Microsoft.AspNetCore.SignalR.Client for the push messages . I have a javascript client which speaks to the server. Since my application could be used in varying internet speeds, i want to keep the transport payload as minimum as possible.

For normal HTTP requests and responses i have enabled the compression by using

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseResponseCompression();
    }
}

But when i looked across internet to do the same with Microsoft.AspNetCore.SignalR.Client, i could not find any doc reference or any examples. So is it possible to enable compression for Microsoft.AspNetCore.SignalR.Client ? If so how. Please help.

My environment

Dotnet core: 3.1.1

Upvotes: 1

Views: 2194

Answers (1)

Markus S.
Markus S.

Reputation: 2812

If you want to optimize for low bandwidth you could use MessagePack instead of Json for the payload serialization.

MessagePack is a fast and compact binary serialization format. It's useful when performance and bandwidth are a concern because it creates smaller messages compared to JSON. The binary 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.

(taken from here).

To make use of message pack you have to activate it on the server like this:

services.AddSignalR()
    .AddJsonProtocol(options => {
        options.PayloadSerializerOptions.PropertyNamingPolicy = null
    });

On the client you have to install the appropriate npm package

npm install @microsoft/signalr-protocol-msgpack

and then initialize your connection appropriately:

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

For more details see:

https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-3.1&tabs=dotnet#jsonmessagepack-serialization-options-1

https://learn.microsoft.com/en-us/aspnet/core/signalr/messagepackhubprotocol?view=aspnetcore-3.1#configure-messagepack-on-the-client-1

Upvotes: 1

Related Questions