Logo

dev-resources.site

for different kinds of informations.

Building Real-Time Applications with SignalR in .NET

Published at
8/17/2024
Categories
dotnet
signalr
realtime
ducdang
Author
minhduc159
Categories
4 categories in total
dotnet
open
signalr
open
realtime
open
ducdang
open
Author
10 person written this
minhduc159
open
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!

realtime Article's
30 articles in total
Favicon
Real-Time Voice Interactions with the WebSocket Audio Adapter
Favicon
Curiosity: Using Ably.io Realtime Messaging as a Lightweight Database
Favicon
Real-Time Voice Interactions over WebRTC
Favicon
Building a Real-Time Collaborative Text Editor with Slate.js
Favicon
Chat API pricing: Comparing MAU and per-minute consumption models
Favicon
Scaling Kafka with WebSockets
Favicon
Build a Real-Time Voting System with Strapi & Instant DB: Part 2
Favicon
WebSocket architecture best practices: Designing scalable realtime systems
Favicon
Build a Real-Time Voting System with Strapi & Instant DB: Part 1
Favicon
Ingesting F1 Telemetry UDP real-time data in AWS EKS
Favicon
Make a real-time, offline first application with Instant
Favicon
Tennis Australia relies on Ably to deliver live experiences for millions of tennis fans worldwide
Favicon
OctoPalm.js || JavaScript library to add real-time, customizable search to your web applications.
Favicon
Building a "Real-Time" Data Integration Platform on AWS
Favicon
Implementing Real-Time Updates with Server-Sent Events (SSE) in C# .NET: A Complete Guide
Favicon
Understanding the Importance of Kafka in High-Volume Data Environments
Favicon
Building Real-Time Applications with SignalR in .NET
Favicon
Not All Market Research Studies Need to Have Real-Time/Live Data Reporting!
Favicon
Real-Time Capabilities in API Integration
Favicon
Migrate from Cord to SuperViz
Favicon
Harnessing Firebase in React with Custom Hooks: A Practical Guide
Favicon
laravel reverb installation process and setup with common mistakes
Favicon
🚀 Want to Boost Your Sports Development? Discover the Benefits of Real-Time Results with SportDevs!
Favicon
Authenticate Realtime Pub/Sub WebSocket clients with Supabase
Favicon
Reliably syncing database and frontend state: A realtime competitor analysis
Favicon
Webhooks: A Mindset Change for Batch Jobs
Favicon
Building a Real-Time Messaging Platform with Kafka
Favicon
Real-Time Data Handling with Firestore: Tracking Pending Orders
Favicon
System Design: Hybrid WebApp using server sent event
Favicon
Real-Time Irish Transit Analytics

Featured ones: