Real-time web apps in .NET with SignalR
Push updates from your ASP.NET Core server to every connected browser instantly. We build a small real-time chat app with SignalR, step by step.
Updated 1 November 20264 min read
There are a few ways to make a web page update itself. You could add a refresh button, or poll the server every few seconds with setInterval and fetch. Polling works, but it wastes requests and is never truly real time: there is always a delay until the next check.
The better option is a WebSocket: a connection between the browser and the server that stays open, so the server can push data to the browser the moment something happens, without the browser asking.
In .NET, the easiest way to do this is SignalR. SignalR is part of ASP.NET Core and gives you a simple API to call methods on connected clients from your server code (and the other way around). It uses WebSockets when they are available and automatically falls back to Server-Sent Events or long polling when they aren't.
Building a real-time chat with SignalR
Let's build a small chat app where every message appears instantly for everyone who has the page open.
Create a new ASP.NET Core Web App (Model-View-Controller) in Visual Studio called ChatApp, or use the CLI:
dotnet new mvc -n ChatAppThe SignalR server is included in ASP.NET Core, so there is no NuGet package to install.
Server side
A hub is the class that clients connect to. Create a Hubs folder with a ChatHub class that inherits from Hub:
using Microsoft.AspNetCore.SignalR;
namespace ChatApp.Hubs;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Send a "ReceiveMessage" event to every connected client
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}Clients can call SendMessage, and the hub forwards the message to all connected clients through the ReceiveMessage event.
Next, register SignalR and the hub in Program.cs:
using ChatApp.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddSignalR(); // Add the SignalR services
var app = builder.Build();
// ... the default middleware and routes from the template ...
app.MapHub<ChatHub>("/chat"); // Clients connect to the hub on /chat
app.Run();Client side
The browser needs the SignalR JavaScript client. In Visual Studio, right-click the project and choose Add > Client-Side Library.... Pick the unpkg provider, search for @microsoft/signalr, choose Choose specific files, select dist/browser/signalr.js and signalr.min.js, and set the target location to wwwroot/js/signalr/.
Not using Visual Studio? The LibMan CLI does the same:
libman install @microsoft/signalr@latest -p unpkg -d wwwroot/js/signalr --files dist/browser/signalr.js --files dist/browser/signalr.min.jsNow create wwwroot/js/chat.js. It connects to the hub, shows incoming messages and sends new ones:
"use strict";
// Connect to the hub on the /chat path we mapped in Program.cs
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chat")
.withAutomaticReconnect()
.build();
const sendButton = document.getElementById("sendButton");
sendButton.disabled = true; // Enabled once we are connected
// Runs every time the hub sends a "ReceiveMessage" event
connection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user} says: ${message}`; // textContent, so messages can't inject HTML
document.getElementById("messagesList").appendChild(li);
});
sendButton.addEventListener("click", async (event) => {
event.preventDefault();
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
try {
await connection.invoke("SendMessage", user, message);
} catch (err) {
console.error(err);
}
});
async function start() {
try {
await connection.start();
sendButton.disabled = false;
} catch (err) {
console.error(err);
setTimeout(start, 5000); // Try again in 5 seconds
}
}
start();A few things worth pointing out:
withAutomaticReconnect()reconnects by itself when the connection drops, for example when the server restarts.- The send button stays disabled until the connection is open, so you can't send messages into the void.
- We use
textContentinstead ofinnerHTML, so nobody can inject HTML or scripts through a chat message.
Finally, replace the contents of Views/Home/Index.cshtml with the chat UI. It uses the Bootstrap 5 classes that ship with the template, and loads the scripts only on this page:
<div class="card">
<div class="card-header">
<h3>Chat</h3>
</div>
<div class="card-body">
<!-- Incoming messages are added here -->
<ul id="messagesList"></ul>
</div>
<div class="card-footer">
<div class="input-group">
<input type="text" id="userInput" class="form-control" placeholder="Username" />
<input type="text" id="messageInput" class="form-control" placeholder="Message" />
<button id="sendButton" class="btn btn-primary">Send</button>
</div>
</div>
</div>
@section Scripts {
<script src="~/js/signalr/dist/browser/signalr.min.js"></script>
<script src="~/js/chat.js"></script>
}Testing
That's it! Run the app with dotnet run (or F5) and open it in two browser tabs. Type a message in one tab and it appears in both instantly:
Where to go from here
Clients.All is only the start. A hub can also send to a single connection (Clients.Client(id)), to everyone except the sender (Clients.Others), or to named groups (Groups.AddToGroupAsync), which is perfect for chat rooms or per-user notifications. Use [Authorize] on a hub to only allow signed-in users.
Conclusion
You now know how SignalR works and how to push updates from your server to the browser in real time. The same pattern works for live dashboards, notifications, multiplayer games and collaborative editing. For more, read the official SignalR documentation by Microsoft.
Frequently asked questions
Do I need to install a NuGet package for SignalR in ASP.NET Core?
No. The SignalR server is part of the ASP.NET Core shared framework. You only need to add the JavaScript client, @microsoft/signalr, to the browser side.
What happens when WebSockets are not available?
SignalR automatically falls back to Server-Sent Events or long polling, so the same code keeps working.
- .NET
- SignalR
- JavaScript
- ASP.NET Core