Introduction
In a real-time application, users expect to see changes as soon as they happen instead of waiting for the browser to request new data. Showing a notification when a task is completed, adding a new task to a list immediately, or displaying the progress of a long-running operation are typical examples.
In this lesson, we will prepare the foundation for the real-time notification and task-tracking application used throughout the course. We will create an ASP.NET Core project on .NET 10, register SignalR services, define a hub, and connect a simple browser client to receive the first real-time message from the server.
We will not add authentication, persistent storage, group management, or a Redis backplane yet. However, the structure created in this lesson will support these features in later lessons.
What is SignalR?
ASP.NET Core SignalR is a library that simplifies real-time communication between a server and connected clients. In a typical HTTP interaction, the client sends a request and the server returns a response. SignalR keeps a communication connection available so the server can send a message to a client when an event occurs.
SignalR uses WebSockets when the environment supports it. If WebSockets cannot be used, SignalR can fall back to another transport. Most application code does not need to know which transport is active. The client connects through a HubConnection, listens for events, and invokes hub methods.
Core components
| Component | Responsibility |
|---|---|
| Hub | Defines the communication contract and server methods used by clients. |
| Hub connection | Represents the client connection to a specific hub endpoint. |
| Server | Produces messages, executes hub methods, and broadcasts to connected clients. |
| Client | Connects to the hub, invokes server methods, and handles server events. |
| Transport | Provides the underlying communication mechanism, such as WebSockets. |
A hub is not a direct client-to-client channel. It is a server-managed mediator. A client can invoke a hub method, and the hub can send messages through targets such as Clients.All, Clients.Caller, or the user and group targets covered later.
Preparing the development environment
You need the .NET 10 SDK, a code editor, and a modern browser. Check the installed SDK from a terminal:
dotnet --versionThe output should begin with 10.0. If several SDKs are installed, use the following command to see all available versions:
dotnet --list-sdksCreate a minimal ASP.NET Core application:
mkdir RealtimeTaskBoard
cd RealtimeTaskBoard
dotnet new web
dotnet add package Microsoft.AspNetCore.SignalR
mkdir Hubs
mkdir wwwrootThe dotnet new web command creates a minimal ASP.NET Core application. This keeps the first lesson focused on the SignalR flow without introducing unnecessary files.
Solution structure and naming
Separating responsibilities becomes important as the application grows. At the end of this lesson, we will use the following basic structure:
RealtimeTaskBoard/
├── Hubs/
│ └── NotificationHub.cs
├── wwwroot/
│ ├── index.html
│ └── app.js
├── Program.cs
└── RealtimeTaskBoard.csprojThe Hubs folder contains SignalR hub classes. The wwwroot folder contains static files served to the browser. In later lessons, we can add separate folders for models, services, DTOs, and authentication components.
Naming hub classes with the Hub suffix improves readability. For example, NotificationHub clearly identifies the hub responsible for notification communication. Hub endpoints should also use meaningful, lowercase routes such as /hubs/notifications.
Creating the first hub
Create Hubs/NotificationHub.cs:
using Microsoft.AspNetCore.SignalR;
namespace RealtimeTaskBoard.Hubs;
public class NotificationHub : Hub
{
public async Task SendNotification(string message)
{
await Clients.All.SendAsync("NotificationReceived", message);
}
}The NotificationHub class derives from Hub. SendNotification is a server method that a client can invoke. The Clients.All.SendAsync call broadcasts the NotificationReceived client event to every connected client.
Notice the two different naming levels. SendNotification is a server method invoked by the client. NotificationReceived is an event raised on clients by the server. They do not need to have the same name, but consistent naming makes troubleshooting easier.
Registering SignalR in the application
Replace the contents of Program.cs with:
using RealtimeTaskBoard.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapHub<NotificationHub>("/hubs/notifications");
app.Run();AddSignalR registers SignalR services with dependency injection. MapHub exposes NotificationHub at /hubs/notifications. The client must use this same route when creating its connection.
UseDefaultFiles and UseStaticFiles allow the browser to load wwwroot/index.html. If these calls are missing, the hub may be correctly configured while the application home page still fails to load as expected.
Creating the browser client
For the first example, we will load the client library from a CDN to keep setup short. In production, pin the version or manage the package with npm and include it in the application output for better control.
Create wwwroot/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Real-Time Task Board</title>
</head>
<body>
<h2>Notifications</h2>
<button id="sendButton">Send test notification</button>
<ul id="messages"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js"></script>
<script src="/app.js"></script>
</body>
</html>Now create wwwroot/app.js:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/notifications")
.withAutomaticReconnect()
.build();
const messages = document.getElementById("messages");
const sendButton = document.getElementById("sendButton");
connection.on("NotificationReceived", (message) => {
const item = document.createElement("li");
item.textContent = message;
messages.appendChild(item);
});
sendButton.addEventListener("click", async () => {
try {
await connection.invoke("SendNotification", "A new task was created.");
} catch (error) {
console.error("The notification could not be sent:", error);
}
});
async function startConnection() {
try {
await connection.start();
console.log("SignalR connection established.");
} catch (error) {
console.error("The connection could not be established:", error);
setTimeout(startConnection, 5000);
}
}
startConnection();HubConnectionBuilder creates the connection object. withUrl specifies the hub route. connection.on registers a client handler for a server event. connection.invoke calls a server method on the hub.
withAutomaticReconnect provides initial support for reconnecting after a dropped connection. In later lessons, we will examine reconnecting states, user interface behavior, and failed-connection policies in more detail.
Running the application
Run the following commands:
dotnet build
dotnet runOpen the address displayed in the terminal. Open the same address in two browser tabs and observe that a notification sent from one tab also appears in the other. This happens because the hub uses Clients.All.
If you want to use a fixed local address, run:
dotnet run --urls "http://localhost:5000"Tracing the communication flow
- The browser starts a SignalR connection to
/hubs/notifications. - The server accepts the connection and creates a connection identifier.
- The user clicks the button.
- The client invokes the
SendNotificationhub method. - The hub broadcasts the message through
Clients.All. - Every connected client executes the
NotificationReceivedhandler. - The client adds the message to the list.
This flow will appear repeatedly throughout the course. In later lessons, the target, data model, authorization rules, or message-producing component will change, but the basic sequence will remain recognizable.
Common mistakes
- 404 Not Found: The client URL and the
MapHubroute may not match. Confirm that both use/hubs/notifications. - signalR is undefined: The JavaScript client library was not loaded or was placed after
app.js. Load the library before the application code. - No message appears: The event name in
connection.onmust match the name passed toSendAsync. - Hub method not found: The method name passed to
invokemust match the server method. Pay attention to capitalization. - The page does not load: Check
UseDefaultFilesandUseStaticFiles, and confirm that the files are underwwwroot. - Different results in two tabs: One tab may be connected to an old server address while the other uses a new address. Inspect the browser console and Network panel.
Practice exercise
Extend the example by adding a task title and priority to SendNotification. Display the result in the browser using this format: “[High] API documentation was updated.”
Verify the following points:
- Two browser tabs connect to the same hub.
- An event sent from one tab appears in the other.
- Server and client event names are consistent.
- The hub route and client URL match.
- A failed connection produces a meaningful message in the browser console.
Conclusion
In this lesson, we created an ASP.NET Core application on .NET 10, registered SignalR services, defined the first hub, and established real-time browser communication. We also examined the roles of hub methods and client events, the Clients.All broadcast target, and basic connection handling.
In the next lessons, we will expand this simple example with task models, a TypeScript client, user and group messaging, notification services, authentication, authorization, and background services. The most important outcome of this lesson is that you can now observe the complete SignalR communication flow from client to server and back to connected clients.
Sources
- https://dotnet.microsoft.com/en-us/download/dotnet/10.0
- https://learn.microsoft.com/en-us/aspnet/core/signalr
- https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr
- https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs
- https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client