Introduction

Modern applications increasingly rely on real-time communication to deliver instant updates and interactive experiences. Whether it's a chat application, live dashboard, stock market tracker, multiplayer game, or notification system, users expect data to update immediately without refreshing the page.

Traditionally, web applications relied on polling techniques where clients repeatedly asked the server for updates. This approach increases server load and introduces delays.

SignalR solves this problem by enabling real-time communication between clients and servers.

In this article, you'll learn what SignalR is, how it works, and how to build real-time applications using SignalR and ASP.NET Core.

What Is SignalR?

SignalR is a real-time communication library for ASP.NET Core that allows servers to push updates to connected clients instantly.

Instead of clients constantly requesting updates, the server can send information whenever data changes.

SignalR supports:

It simplifies the process of adding real-time functionality to web applications.

Why Use SignalR?

SignalR offers several advantages over traditional communication methods.

Instant Updates

Clients receive updates immediately when data changes.

Reduced Server Requests

No need for continuous polling.

Better User Experience

Applications feel more responsive and interactive.

Cross-Platform Support

SignalR works with:

Automatic Connection Management

SignalR handles connection establishment and reconnection automatically.

How SignalR Works

SignalR creates a persistent connection between clients and the server.

Typical workflow:

Client
   ↕
SignalR Hub
   ↕
Server

When the server sends data, connected clients receive it instantly.

This communication is bidirectional, meaning both the server and clients can exchange messages.

SignalR Transport Methods

SignalR automatically chooses the best available communication method.

Supported transports include:

WebSockets

Preferred option for maximum performance.

Client ↔ Server

Server-Sent Events (SSE)

Used when WebSockets are unavailable.

Long Polling

Fallback option for older environments.

SignalR automatically selects the most appropriate transport.

Common Real-Time Use Cases

SignalR is commonly used for:

Any application requiring immediate updates can benefit from SignalR.

Creating an ASP.NET Core Project

Create a new ASP.NET Core project.

dotnet new webapp -n SignalRDemo

Navigate to the project folder.

cd SignalRDemo

Run the application.

dotnet run

The project is now ready for SignalR integration.

Adding SignalR

Install the SignalR package.

dotnet add package Microsoft.AspNetCore.SignalR

This package provides all required SignalR functionality.

Creating a SignalR Hub

A Hub acts as the communication center between clients and the server.

Create a new file named:

ChatHub.cs

Add the following code.

using Microsoft.AspNetCore.SignalR;

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

The hub receives messages and broadcasts them to all connected clients.

Registering SignalR Services

Open Program.cs.

Add SignalR services.

builder.Services.AddSignalR();

Map the hub endpoint.

app.MapHub<ChatHub>("/chatHub");

SignalR is now configured and ready to accept connections.

Creating a Client Connection

Add the SignalR JavaScript library.

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

Create a connection.

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

This establishes communication with the server.

Starting the Connection

Start the connection after building it.

connection.start()
    .then(() => {
        console.log(
            "Connected"
        );
    });

The client is now connected to the SignalR hub.

Receiving Messages

Register an event handler.

connection.on(
    "ReceiveMessage",
    (user, message) => {
        console.log(
            user + ": " + message
        );
    }
);

Whenever the server sends a message, the client receives it immediately.

Sending Messages from the Client

Invoke a hub method.

connection.invoke(
    "SendMessage",
    "John",
    "Hello SignalR"
);

The server receives the message and broadcasts it to all connected users.

Building a Simple Chat Application

A chat application is one of the most common SignalR examples.

Workflow:

User A
   ↓
SignalR Hub
   ↓
User B

Messages appear instantly for all connected users.

This eliminates the need for manual page refreshes.

Sending Notifications

SignalR is ideal for notification systems.

Example:

await Clients.User(userId)
    .SendAsync(
        "Notification",
        "Order Approved"
    );

Users receive notifications immediately when events occur.

Common examples include:

Using Groups

Groups allow messages to be sent to specific users.

Example:

await Groups.AddToGroupAsync(
    Context.ConnectionId,
    "Developers"
);

Send a message to the group.

await Clients.Group("Developers")
    .SendAsync(
        "ReceiveMessage",
        "Welcome Developers"
    );

Groups are useful for:

Managing User Connections

SignalR provides connection lifecycle events.

User connected:

public override async Task OnConnectedAsync()
{
    await base.OnConnectedAsync();
}

User disconnected:

public override async Task OnDisconnectedAsync(
    Exception exception)
{
    await base.OnDisconnectedAsync(
        exception
    );
}

These methods help track active users.

Real-Time Dashboards

SignalR is widely used for live dashboards.

Example metrics:

Architecture:

Data Source
      ↓
ASP.NET Core
      ↓
SignalR
      ↓
Dashboard

Users see updates as soon as data changes.

SignalR with Blazor

SignalR powers many real-time features in Blazor applications.

Examples:

Blazor and SignalR work together seamlessly within the ASP.NET ecosystem.

Scaling SignalR Applications

As applications grow, multiple servers may be required.

Example:

Load Balancer
     ↓
Server 1
Server 2
Server 3

To synchronize messages across servers, organizations often use:

These solutions ensure all users receive updates regardless of which server they connect to.

Using Azure SignalR Service

Azure SignalR Service simplifies scaling.

Benefits include:

Large applications often use Azure SignalR for production deployments.

Security Considerations

Real-time applications must be secured properly.

Recommended practices:

Example:

[Authorize]
public class ChatHub : Hub
{
}

This ensures only authenticated users can connect.

Best Practices

When building SignalR applications:

Following these practices improves reliability and performance.

Common Mistakes to Avoid

Developers often encounter these issues:

Avoiding these mistakes leads to more stable real-time applications.

Real-World Applications

SignalR is commonly used for:

Chat Platforms

Real-time messaging between users.

Live Dashboards

Instant metric updates.

Financial Applications

Stock prices and trading updates.

Collaboration Tools

Shared editing experiences.

Monitoring Systems

Real-time infrastructure monitoring.

Its flexibility makes it suitable for many modern applications.

Conclusion

SignalR makes it easy to add real-time functionality to ASP.NET Core applications. By maintaining persistent connections between clients and servers, it enables instant communication without the overhead of continuous polling.

Whether you're building chat systems, notification platforms, dashboards, collaborative tools, or monitoring applications, SignalR provides a reliable and scalable solution for real-time communication.

Combined with ASP.NET Core's performance and flexibility, SignalR allows developers to create highly interactive applications that deliver a modern user experience.