In today’s fast-paced digital world, delivering the latest information without refreshing the user interface is crucial. SignalR is a powerful library in .NET that allows you to push content from your server-side code to any connected clients in real-time. This post will guide you through the basics of using SignalR to build real-time applications.
Why SignalR?
SignalR simplifies the process of adding real-time functionality to your applications. It abstracts away the complexities of managing connections and message transport, allowing you to focus on building features.
Getting Started with SignalR
- Install the Package: Begin by installing the Microsoft.AspNetCore.SignalR.Client NuGet package.
dotnet add package Microsoft.AspNetCore.SignalR.Client
- Create a Hub: The Hub is the central component responsible for managing clients and sending messages. Create a
NotificationsHub
by inheriting from the baseHub
class.
using Microsoft.AspNetCore.SignalR;
public class NotificationsHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
- Register Services: Register the SignalR services by calling the
AddSignalR
method and map your hub using theMapHub<T>
method.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationsHub>("/notificationsHub");
});
}
Testing SignalR
To test your SignalR implementation, you can use Postman’s WebSocket Request to connect to the NotificationsHub
. This allows you to send and receive messages in real-time, ensuring your setup works correctly.
- Connect to the NotificationsHub
- Set the communication protocol to JSON
- Send messages to call the
NotificationsHub
methods
All messages need to end with a null termination character, which is just the ASCII character 0x1E
.
Let's start off by sending this message to set the communication protocol to JSON:
{
"protocol": "json",
"version": 1
}?
You'll receive this response from the hub.
We need a slightly different message format to call a message on the Hub
. The key is specifying the arguments
and target, which is the actual hub method we want to call.
Let's say we want to call the SendNotification
method on the NotificationsHub
:
{
"arguments": ["This is the notification message."],
"target": "SendNotification",
"type": 1
}
This will be the response we get back from the NotificationsHub
:
Strongly Typed Hubs
SignalR supports strongly typed hubs, which help enforce method parameters and reduce errors. Define a client interface and update your hub class to inherit from Hub<T>
.
public interface INotificationsClient
{
Task ReceiveMessage(string user, string message);
}
public class NotificationsHub : Hub<INotificationsClient>
{
public async Task SendMessage(string user, string message)
{
await Clients.All.ReceiveMessage(user, message);
}
}
Sending Notifications
Use the IHubContext<THub, TClient>
interface to send notifications to specific users. SignalR tracks users internally, allowing you to target messages based on user identifiers.
public class NotificationService
{
private readonly IHubContext<NotificationsHub, INotificationsClient> _hubContext;
public NotificationService(IHubContext<NotificationsHub, INotificationsClient> hubContext)
{
_hubContext = hubContext;
}
public async Task SendNotification(string userId, string message)
{
await _hubContext.Clients.User(userId).ReceiveMessage("System", message);
}
}
Conclusion
Adding real-time functionality to your application with SignalR can significantly enhance user experience. Start building real-time apps in .NET today and see the difference it makes!
Top comments (1)
Great article. I have also written about this in a 7 part series which includes trouble shooting information.