SignalR is an open-source library that allows for real-time communication between the server and the client. It gives server-side code the ability to send asynchronous updates to connected clients. Therefore, it is perfect for use in applications requiring real-time functionality, such as live notifications, chats, or collaborative tools. For Blazor, it offers two-way smooth communication between the client and the server, hence a very interactive and efficient user experience.
SignalR in Blazor Server Applications
Blazor Server applications inherently integrate SignalR to establish persistent connections between the client and server. This connection allows the server to push updates to the client in real-time whenever the server-side state changes.
Key Features in SignalR with Blazor Server
- Persistent Connection: SignalR leverages WebSockets or other transport alternatives, including Server-Sent Events or Long Polling, to permit continuous connectivity between the client and server.
- Real-time UI updates: Any changes on the server are automatically reflected in the client UI without refreshing the page.
- Efficient Updates: SignalR transfers only the differences rather than the entire page, optimizing data transfer.
1. Create a SignalR Hub
A Hub is a central point for communication between clients and the server.
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
2. Configure SignalR in the Server
In your Program.cs, map the Hub endpoint:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapHub<ChatHub>("/chathub");
3. Use SignalR in a Blazor Component
Include the SignalR JavaScript library in _Host.cshtml:
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js"></script>
Set up a SignalR connection in your Blazor component:
@inject IJSRuntime JS
@code {
private HubConnection? hubConnection;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
// Handle incoming messages
});
await hubConnection.StartAsync();
}
private async Task SendMessage()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", "User", "Hello, world!");
}
}
}
In this example, the SendMessage method allows the client to send messages to the server, and the ReceiveMessage method handles incoming messages from the server.
SignalR in Blazor WebAssembly Applications
Unlike Blazor Server, SignalR is not built into Blazor WebAssembly by default. However, you can explicitly integrate SignalR to enable real-time features like chat or live notifications.

Satyaprakash SamantarayPosted Dec 9, 2024, 5:14 PM
Where is the output?