development

How to Use SignalR for Real-Time Communication in .NET Apps

What is SignalR?

SignalR is a Microsoft library that enables your web app to send and receive messages instantly,  without requiring page reloads.

Think of it like walkie-talkies between the server and your users. The moment something changes (such as someone sending a message), all connected users see it immediately.

 Why Use SignalR?

  • No need for constant page refresh
  • Built into ASP.NET Core
  • Uses the best communication method available (WebSockets, Server-Sent Events, or Long Polling)
  • Works great with JavaScript, Blazor, Xamarin, and even mobile apps

 Real-Time Communication Use Cases

You’d use SignalR in scenarios where speed and freshness of data matter:

Use CaseDescription
Chat AppsSend and receive messages in real-time
Live DashboardsStock prices, system monitoring, or real-time analytics
NotificationsAlert users instantly when something happens
Collaborative PlatformsGoogle Docs-style co-editing features
Multiplayer GamesReal-time movement, chat, and scores
IoT Monitoring SystemsDisplay sensor data as it updates

Step-by-Step Tutorial: Build a Real-Time Chat App with SignalR

Let’s build a real-time chat app using SignalR in .NET 6+ and JavaScript. We’ll go slow and explain each part.

 Step 1: Create a New ASP.NET Core MVC Project

Using Visual Studio:

  1. Open Visual Studio
  2. Go to File > New > Project.
  3. Choose ASP.NET Core Web App (Model-View-Controller)
  4. Click Next, name it SignalRChatApp, then click Create
  5. Choose .NET 6.0 (Long-term support) and click Create.

 Step 2: Install the SignalR NuGet Package

If it’s not already added, install it:

Using Package Manager Console:

powershell

CopyEdit

Install-Package Microsoft.AspNetCore.SignalR

Or via .NET CLI:

bash

CopyEdit

dotnet add package Microsoft.AspNetCore.SignalR

 Step 3: Create a SignalR Hub

Add a new folder called Hubs. Inside it, create a class named ChatHub.cs.

csharp

CopyEdit

using Microsoft.AspNetCore.SignalR;

namespace SignalRChatApp.Hubs

{

    public class ChatHub: Hub

    {

        public async Task SendMessage(string user, string message)

        {

            await Clients.All.SendAsync(“ReceiveMessage”, user, message);

        }

    }

}

 Explanation:

  • Hub: A central place where the server and clients talk.
  • SendMessage: Called by the client to broadcast a message.
  • Clients.All.SendAsync(…): Sends the message to everyone connected.

 Step 4: Update Program.cs to Register SignalR

Open your Program.cs and update it like this:

csharp

CopyEdit

using SignalRChatApp.Hubs;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddSignalR(); // Add SignalR services

var app = builder.Build();

app.UseStaticFiles();

app.UseRouting();

app.MapControllerRoute(

    name: “default”,

    pattern: “{controller=Home}/{action=Index}/{id?}”);

app.MapHub<ChatHub>(“/chathub”); // Register the SignalR hub

app.Run();

 Step 5: Add JavaScript Frontend for SignalR

Open Views/Home/Index.cshtml and replace the body with this code:

html

CopyEdit

<div class=”container”>

    <h2>SignalR Real-Time Chat</h2>

    <input type=”text” id=”userInput” placeholder=”Enter your name” />

    <input type=”text” id=”messageInput” placeholder=”Type a message” />

    <button onclick=”sendMessage()”>Send</button>

    <ul id=”messagesList”></ul>

</div>

<script src=”https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js”></script>

<script>

    const connection = new signalR.HubConnectionBuilder()

        .withUrl(“/chathub”)

        .build();

    Connection.on(“ReceiveMessage”, function (user, message) {

        const msg = document.createElement(“li”);

        msg.textContent = `${user}: ${message}`;

        document.getElementById(“messagesList”).appendChild(msg);

    });

    connection.start().catch(function (err) {

        return console.error(err.toString());

    });

    function sendMessage() {

        const user = document.getElementById(“userInput”).value;

        const message = document.getElementById(“messageInput”).value;

        connection.invoke(“SendMessage”, user, message)

            .catch(function (err) {

                return console.error(err.toString());

            });

    }

</script>

 This script does three main things:

  1. Connects to the hub
  2. Listens for incoming messages
  3. Sends messages when the user clicks “Send”

 Step 6: Run the App

  1. Press F5 or click the green play button in Visual Studio.
  2. Open two browser tabs with the app running.
  3. Send a message in one tab, and it appears in the other immediately.

 You just made your first real-time app using SignalR!

Advanced Features in SignalR

Once you’re comfy with the basics, try these:

1. SignalR Groups

You can add users to specific groups (e.g., rooms or channels):

csharp

CopyEdit

await Groups.AddToGroupAsync(Context.ConnectionId, “Admins”);

2. Private Messaging

Send a message to a specific user:

csharp

CopyEdit

await Clients.User(userId).SendAsync(“ReceiveMessage”, message);

3. Authentication Integration

SignalR works with ASP.NET authentication and identity, allowing secure messaging between users.

4. Scale-out with Redis or Azure

To support multiple users across servers, consider using Redis or Azure SignalR Service.

Common Issues & How to Fix Them

ProblemSolution
JavaScript error: connection not definedEnsure the SignalR script is loaded before your custom script
404 error on /chathubDouble-check the MapHub route in Program.cs
Messages not showingConfirm the client on() method matches the server method name
Not working on productionEnsure WebSockets are enabled on the server or use Azure SignalR

FAQs

Can I use SignalR in Blazor?

Yes! SignalR is actually what powers Blazor Server. You can also use it in Blazor WebAssembly via JavaScript interop.

Does SignalR work on mobile?

Absolutely. You can connect using Xamarin, MAUI, Android, and iOS using platform-specific SignalR client libraries.

What if WebSockets aren’t supported?

No worries, SignalR automatically falls back to Server-Sent Events or Long Polling, depending on what the browser/server supports.

Can I broadcast messages to specific users?

Yes! You can send messages to a specific user, group, or connection using:
csharp
CopyEdit
Clients.User(“userId”).SendAsync(…);
Clients.Group(“groupName”).SendAsync(…);
Clients.Client(“connectionId”).SendAsync(…);

Conclusion 

SignalR is one of those tools that can take your app from “just functional” to “mind-blowingly interactive.” Whether you’re building a chat app, a stock tracker, or a notification system, SignalR’s got your back.

Leave a Reply

Your email address will not be published. Required fields are marked *