Search code examples
signalrblazor-server-side

Artificially throttling SignalR connection in server-side Blazor


In order to test my Blazor application on slow / unreliable networks, I am looking for a way to artificially throttle websocket messages being sent to or from Blazor. Unfortunately Chrome still doesn't support throttling websocket connections.

I've delved into the bowels of ASP.NET's SignalR code but can't find any obvious services I can extend, nor any easy way to add SignalR middlware.

Extending HubDispatcher looks the most promising, however this is an internal class.

Are there any message processing extension points available in either Blazor or SignalR classes?


Solution

  • I managed to do this with HubFilters:

    public class LaggingHubFilter : IHubFilter
    {
        public async ValueTask<object> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object>> next)
        {
            await Task.Delay(200).ConfigureAwait(true);
    
            return await next(invocationContext);
        }
    }
    

    Then register it in Program.cs:

    services.AddServerSideBlazor().AddHubOptions(h => h.AddFilter<LaggingHubFilter>());