How to Implement Real-Time Communication in .NET 8 Minimal APIs Using SignalR: A Step-by-Step Guide

leandroveiga

Leandro Veiga

Posted on October 16, 2024

How to Implement Real-Time Communication in .NET 8 Minimal APIs Using SignalR: A Step-by-Step Guide

As modern applications continue to evolve, real-time communication has become a crucial feature for enhancing user experience. Whether it's live notifications, collaborative tools, or live updates in dashboards, SignalR combined with Minimal APIs in .NET 8 offers a simple and efficient way to implement real-time functionality.

In this blog post, we'll explore how to integrate SignalR with Minimal APIs in .NET 8 to enable real-time communication in your application.


What is SignalR?

SignalR is a library that enables real-time web functionality in .NET applications. It allows server-side code to push updates to clients instantly. SignalR supports various transport methods, including WebSockets, Server-Sent Events, and Long Polling, depending on the capabilities of the client and server.

Some typical use cases for SignalR include:

  • Live chat applications
  • Real-time notifications
  • Collaborative document editing
  • Interactive dashboards that update in real-time

1. Setting Up a Minimal API with SignalR

To get started, let's first create a Minimal API project in .NET 8 and integrate SignalR for real-time communication.

Step 1: Install SignalR Package

In your .NET 8 project, install the Microsoft.AspNetCore.SignalR package via NuGet:

dotnet add package Microsoft.AspNetCore.SignalR
Enter fullscreen mode Exit fullscreen mode

Step 2: Define a Hub for Real-Time Communication

A Hub is a class in SignalR that acts as a high-level pipeline, allowing the server to communicate with clients. Let's define a simple hub for sending messages.

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
Enter fullscreen mode Exit fullscreen mode

The SendMessage method broadcasts the message to all connected clients via the Clients.All.SendAsync method.

Step 3: Configure SignalR in Program.cs

Next, configure the SignalR middleware in your Minimal API project. You can add a SignalR hub in Program.cs by registering it as part of the app's request pipeline.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Add SignalR middleware
app.MapHub<ChatHub>("/chathub");

app.Run();
Enter fullscreen mode Exit fullscreen mode

This exposes a /chathub endpoint that clients can connect to for real-time communication.


2. Creating a Client to Connect to the SignalR Hub

SignalR supports various client types, including JavaScript, .NET, and Java. For simplicity, let's create a JavaScript client to connect to our SignalR hub.

Step 1: Add SignalR Client Library

To connect to the SignalR hub from the front-end, include the SignalR JavaScript library in your client application. You can install it using a CDN or via npm:

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.0/signalr.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Step 2: Connect to the Hub and Handle Messages

Here's an example of how to connect to the SignalR hub and send/receive messages using JavaScript:

<script type="text/javascript">
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chathub")
        .build();

    // Start the connection
    connection.start().then(() => {
        console.log("Connected to SignalR");
    }).catch(err => console.error(err));

    // Send message to the hub
    document.getElementById("sendButton").addEventListener("click", function () {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;
        connection.invoke("SendMessage", user, message).catch(err => console.error(err));
    });

    // Receive messages from the hub
    connection.on("ReceiveMessage", function (user, message) {
        const li = document.createElement("li");
        li.textContent = `${user}: ${message}`;
        document.getElementById("messagesList").appendChild(li);
    });
</script>
Enter fullscreen mode Exit fullscreen mode

This script connects to the /chathub endpoint, sends a message when the user clicks a button, and listens for new messages broadcasted by the server.


3. Enhancing SignalR with Real-Time Notifications

Now that we've set up the basic messaging system, let's look at how you can use SignalR for real-time notifications. In many applications, such as dashboards or collaborative tools, users expect instant updates when certain actions occur.

Example: Sending Real-Time Notifications

Imagine a scenario where your application needs to notify users whenever a new order is placed. Here's how you can broadcast a notification from the backend using SignalR.

public class NotificationHub : Hub
{
    public async Task SendOrderNotification(string orderId)
    {
        await Clients.All.SendAsync("ReceiveNotification", $"New order received: {orderId}");
    }
}
Enter fullscreen mode Exit fullscreen mode

You can trigger this method from any part of your application, such as after an order is processed:

public async Task ProcessOrder(string orderId)
{
    // Process the order...

    // Notify clients
    var hubContext = app.Services.GetRequiredService<IHubContext<NotificationHub>>();
    await hubContext.Clients.All.SendAsync("ReceiveNotification", $"New order: {orderId}");
}
Enter fullscreen mode Exit fullscreen mode

On the client-side, you can listen for these notifications and update the UI in real-time.

<script type="text/javascript">
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/notificationhub")
        .build();

    connection.start().then(() => {
        console.log("Connected to Notification Hub");
    }).catch(err => console.error(err));

    connection.on("ReceiveNotification", function (message) {
        alert(message);
    });
</script>
Enter fullscreen mode Exit fullscreen mode

4. Handling Disconnections and Reconnection

One of the challenges of real-time communication is handling network interruptions or client disconnections. SignalR provides built-in functionality to manage reconnections seamlessly.

Example: Automatic Reconnection in SignalR

In the JavaScript client, you can configure automatic reconnections by adding .withAutomaticReconnect() to the HubConnectionBuilder.

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub")
    .withAutomaticReconnect()
    .build();

connection.onreconnecting((error) => {
    console.log(`Connection lost: ${error}. Trying to reconnect...`);
});

connection.onreconnected(() => {
    console.log("Reconnected to SignalR");
});
Enter fullscreen mode Exit fullscreen mode

This ensures that your application attempts to reconnect if the connection is lost, improving the overall user experience during network instability.


5. Securing SignalR Hubs

Security is crucial in real-time communication, especially when dealing with sensitive data. You can secure SignalR hubs by implementing authentication and authorization using JWT tokens or other authentication methods.

Example: Securing SignalR with JWT

First, configure your SignalR server to use JWT authentication:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            // Add your token validation logic here
        };
    });

app.MapHub<ChatHub>("/chathub").RequireAuthorization();
Enter fullscreen mode Exit fullscreen mode

Then, on the client-side, attach the JWT token when connecting to the hub:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub", { accessTokenFactory: () => localStorage.getItem("jwtToken") })
    .build();
Enter fullscreen mode Exit fullscreen mode

This ensures that only authenticated users can access the hub, enhancing the security of your real-time communication.


Conclusion

By integrating SignalR with Minimal APIs in .NET 8, you can easily build powerful real-time communication features into your application. Whether you're building live chat systems, notification services, or interactive dashboards, SignalR makes it simple to deliver instant updates to users.

In this post, we covered how to:

  • Set up a real-time messaging system using SignalR.
  • Build a JavaScript client to communicate with the hub.
  • Implement real-time notifications for users.
  • Handle reconnections and ensure the system is fault-tolerant.
  • Secure SignalR hubs with authentication.

Real-time communication can greatly enhance user experience, and with .NET 8's minimal API structure and SignalR, you have a streamlined way to implement this functionality.

💖 💪 🙅 🚩
leandroveiga
Leandro Veiga

Posted on October 16, 2024

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

Sign up to receive the latest update from our blog.

Related