Building Real-Time Applications with SignalR in .NET

minhduc159

Duc Dang

Posted on August 17, 2024

Building Real-Time Applications with SignalR in .NET

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
Enter fullscreen mode Exit fullscreen mode
  • Create a Hub: The Hub is the central component responsible for managing clients and sending messages. Create a NotificationsHub by inheriting from the base Hub class.
using Microsoft.AspNetCore.SignalR;

public class NotificationsHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Register Services: Register the SignalR services by calling the AddSignalRmethod and map your hub using the MapHub<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");
    });
}
Enter fullscreen mode Exit fullscreen mode

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.

Postman’s WebSocket Request
Here's what we need to do:

  • Connect to the NotificationsHub
  • Set the communication protocol to JSON
  • Send messages to call the NotificationsHubmethods

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
}?
Enter fullscreen mode Exit fullscreen mode

You'll receive this response from the hub.

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
}
Enter fullscreen mode Exit fullscreen mode

This will be the response we get back from the NotificationsHub:

Response back from 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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!

💖 💪 🙅 🚩
minhduc159
Duc Dang

Posted on August 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related