In this lesson, you will learn how to build pipeline filters to intercept, inspect, and potentially block messages before they are processed by your SignalR Hub methods.
The Concept of Hub Filters
In advanced SignalR architectures, you often need a cross-cutting concern—like logging message metadata, validating arguments, or sanitizing input—without bloating your Hub classes with repetitive boilerplate code. SignalR provides the IHubFilter interface, which allows you to hook into the invocation pipeline.
Think of an IHubFilter as middleware for your Hub methods. It acts as a gatekeeper that wraps the execution of the Hub method, allowing you to run logic before the method executes, after it returns, or even when it throws an exception.
Implementing a Filter
To create a filter, implement IHubFilter. The core method is InvokeMethodAsync, which gives you access to the HubInvocationContext.
public class LoggingFilter : IHubFilter
{
public async ValueTask<object?> InvokeMethodAsync(
HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
{
// 1. Logic BEFORE the hub method
Console.WriteLine($"Calling {invocationContext.HubMethodName}");
try
{
// 2. Call the next filter or the hub method itself
return await next(invocationContext);
}
catch (Exception ex)
{
// 3. Logic if an exception occurs
Console.WriteLine($"Error in {invocationContext.HubMethodName}: {ex.Message}");
throw;
}
}
}
Registering the Pipeline
Once your filter is defined, you must register it in your Program.cs when configuring SignalR services. You can add it globally to all Hubs or selectively to specific ones:
builder.Services.AddSignalR(options =>
{
options.AddFilter<LoggingFilter>();
});
By using these filters, you maintain a "Clean Hub" architecture. Your Hub methods remain focused on core business logic, while infrastructure concerns like auditing, performance measurement, or validation are decoupled into reusable components. Since these operate within the HubInvocationContext, you can easily access the caller's connection ID or injected services, keeping your real-time pipeline secure and observable.
Key Takeaway: Custom Message Filters act as a middleware layer for SignalR Hubs, allowing you to intercept and control the invocation pipeline to enforce cross-cutting requirements without cluttering your Hub logic.