Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR .net core Filters

Does SignalR have a similar options as the MVC Filters described here?

With MVC I can create an Action Filter (derived from IAsyncActionFilter) and use it as an attribute on a MVC method.

For example:

[ServiceFilter(typeof(MyCustomAsyncActionFilter))]
public async Task<IActionResult> GetAlbums() { }

With the above example, MyCustomAsyncActionFilter can then be implemented to handle custom code that needs to be executed prior to executing the method.

What's the equivalent of the above when working with SignalR methods?

like image 631
Exocomp Avatar asked Sep 11 '25 10:09

Exocomp


2 Answers

AFAIK there is no feature like ASP.NET SignalR hub pipelines in SignalR Core yet (see this GitHub issue) and the MVC filters don't apply to SignalR.

A workaround might be to implement your own HubDispatcher and override the DispatchMessageAsync method:

public class CustomHubDispatcher<THub> : DefaultHubDispatcher<THub> where THub : Hub
{
    public CustomHubDispatcher(
        IServiceScopeFactory serviceScopeFactory,
        IHubContext<THub> hubContext,
        IOptions<HubOptions<THub>> hubOptions,
        IOptions<HubOptions> globalHubOptions,
        ILogger<CustomHubDispatcher<THub>> logger) : base(serviceScopeFactory, hubContext, hubOptions, globalHubOptions, logger)
    {
    }

    public override Task DispatchMessageAsync(HubConnectionContext connection, HubMessage hubMessage)
    {
        switch (hubMessage)
        {
            case InvocationMessage invocationMessage:
                {
                    // do something here
                    break;
                }
        }
        return base.DispatchMessageAsync(connection, hubMessage);
    }
}

and use it in ConfigureServices:

services.AddSignalR();
services.AddSingleton(typeof(HubDispatcher<>), typeof(CustomHubDispatcher<>));
like image 181
scharnyw Avatar answered Sep 14 '25 01:09

scharnyw


.NET 5 supports Hub Filters

From the docs:

services.AddSignalR(options =>
{
    // Global filters will run first
    options.AddFilter<CustomFilter>();
}).AddHubOptions<ChatHub>(options =>
{
    // Local filters will run second
    options.AddFilter<CustomFilter2>();
});

Filters need to implement IHubFilter

like image 26
Richard Szalay Avatar answered Sep 14 '25 02:09

Richard Szalay