Reputation: 1537
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?
Upvotes: 4
Views: 2567
Reputation: 84754
.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
Upvotes: 3
Reputation: 2686
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<>));
Upvotes: 4