ASP.NET - SignalR for Real-Time Communication in ASP.NET Core

Introduction

Modern web applications often require information to be updated instantly without requiring users to refresh the webpage. Features such as live chat, online gaming, stock market updates, collaborative editing, online auctions, and notification systems depend on real-time communication between the client and the server. Traditional web applications follow the request-response model, where the client requests data, and the server responds. This approach is not suitable for applications where data changes frequently.

SignalR is a real-time communication library provided by ASP.NET Core that enables servers to send data to connected clients instantly. It abstracts the complexity of managing different communication protocols and automatically selects the best available transport method. SignalR makes it easy to build interactive web applications that provide immediate updates to users with minimal development effort.


What is SignalR?

SignalR is an open-source library developed by Microsoft that simplifies adding real-time functionality to ASP.NET Core applications. It establishes a persistent connection between the client and the server, allowing both sides to send messages whenever necessary.

Unlike traditional HTTP communication, where the client initiates every request, SignalR enables the server to push information directly to connected clients.

For example, in a chat application:

  • User A sends a message.

  • The server immediately receives it.

  • SignalR instantly delivers the message to User B without requiring User B to refresh the page.

This creates a seamless and interactive user experience.


Why Use SignalR?

SignalR offers several advantages for developers creating modern web applications.

Instant Data Updates

Users receive new information immediately after it becomes available.

Example:
A cricket score website updates every ball without refreshing the browser.


Reduced Network Requests

Without SignalR, browsers repeatedly send requests to check for updates.

With SignalR:

  • One persistent connection is maintained.

  • The server sends updates only when needed.

  • Network traffic is significantly reduced.


Better User Experience

Real-time communication creates smooth and responsive applications.

Examples include:

  • Chat applications

  • Live dashboards

  • Online collaboration

  • Real-time notifications


Automatic Transport Selection

SignalR automatically chooses the best communication protocol supported by both the client and server.

Developers do not need to manually configure transport methods.


Cross-Platform Support

SignalR supports various client platforms including:

  • Web browsers

  • Mobile applications

  • Desktop applications

  • IoT devices


How SignalR Works

SignalR follows a client-server communication model.

The communication process is:

  1. Client requests a SignalR connection.

  2. Server establishes a persistent connection.

  3. Client sends messages to the server.

  4. Server processes the message.

  5. Server broadcasts the message to one or multiple clients.

  6. Connected clients receive updates instantly.

The connection remains active until either the client disconnects or the server closes the connection.


SignalR Architecture

SignalR mainly consists of three components.

1. Hub

A Hub is the central communication point.

It receives messages from clients and sends messages back.

Responsibilities include:

  • Receiving client requests

  • Broadcasting messages

  • Managing connected users

  • Sending notifications

Example:

A ChatHub receives chat messages and sends them to all connected users.


2. Client

The client is the application connected to the SignalR server.

Examples:

  • ASP.NET Core web application

  • JavaScript application

  • Android app

  • iOS app

  • Windows application

Clients listen for server messages and can also send messages to the server.


3. Server

The ASP.NET Core server hosts the SignalR Hub.

It manages:

  • Client connections

  • User authentication

  • Message routing

  • Group communication

  • Connection lifetime


SignalR Communication Flow

Consider an online chat application.

Step 1

A user opens the chat page.

Step 2

The browser establishes a SignalR connection.

Step 3

The server registers the connection.

Step 4

The user sends a message.

Step 5

The Hub receives the message.

Step 6

The Hub broadcasts the message.

Step 7

All connected users instantly receive the message.

This entire process usually takes only a fraction of a second.


Transport Methods Used by SignalR

SignalR automatically selects the most suitable communication method.

WebSockets

This is the preferred transport.

Features include:

  • Full duplex communication

  • Fast performance

  • Low latency

  • Efficient for real-time applications

Suitable for:

  • Live chat

  • Online gaming

  • Financial applications


Server-Sent Events (SSE)

If WebSockets are unavailable, SignalR may use Server-Sent Events.

Characteristics:

  • One-way communication

  • Server sends updates

  • Client cannot send data over the same channel

Used mainly for live updates.


Long Polling

If neither WebSockets nor SSE are supported, SignalR falls back to Long Polling.

In Long Polling:

  • Client sends a request.

  • Server waits until data is available.

  • Response is sent.

  • Client immediately sends another request.

Although slower than WebSockets, it ensures compatibility with older environments.


Creating a SignalR Hub

A Hub is created by inheriting the Hub class.

Example:

using Microsoft.AspNetCore.SignalR;

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

This Hub receives messages from one client and broadcasts them to all connected clients.


Registering SignalR

SignalR services are registered in the application configuration.

Example:

builder.Services.AddSignalR();

Mapping the Hub:

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

The Hub becomes accessible at:

/chatHub

JavaScript Client Example

Connecting from JavaScript:

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

connection.start();

Listening for server messages:

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

Sending a message:

connection.invoke("SendMessage", "Alice", "Hello Everyone");

Broadcasting Messages

SignalR supports different broadcasting options.

Send to Everyone

await Clients.All.SendAsync("ReceiveMessage", message);

Every connected client receives the message.


Send to Caller

await Clients.Caller.SendAsync("ReceiveMessage", message);

Only the sender receives the message.


Send to Others

await Clients.Others.SendAsync("ReceiveMessage", message);

Every connected user except the sender receives the message.


Send to Specific User

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

Only one user receives the message.


Send to Groups

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

Only members of the Developers group receive the message.


SignalR Groups

Groups allow developers to organize users.

Examples include:

  • Chat rooms

  • Teams

  • Departments

  • Project members

  • Online classrooms

Adding a user to a group:

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

Removing a user:

await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Students");

Groups simplify broadcasting to a selected audience.


Connection Management

SignalR automatically manages client connections.

Useful events include:

OnConnectedAsync()

Runs when a client connects.

OnDisconnectedAsync()

Runs when a client disconnects.

Developers often use these methods to:

  • Track online users

  • Log activity

  • Clean up resources

  • Update user status


Authentication and Authorization

SignalR integrates with ASP.NET Core authentication.

Developers can:

  • Authenticate users

  • Restrict Hub access

  • Authorize specific methods

  • Identify connected users securely

This ensures only authorized users participate in real-time communication.


Common Use Cases

SignalR is widely used in:

  • Live chat applications

  • Customer support systems

  • Video conferencing platforms

  • Online multiplayer games

  • Real-time stock market dashboards

  • Sports score updates

  • Online auction platforms

  • Social media notifications

  • Collaborative document editing

  • Project management tools

  • Healthcare monitoring systems

  • Smart home automation

  • Logistics tracking systems

  • Online education platforms

  • Banking transaction alerts


Advantages of SignalR

  • Easy to integrate with ASP.NET Core applications.

  • Provides real-time communication with low latency.

  • Automatically selects the best transport protocol.

  • Supports broadcasting to all clients, selected users, or groups.

  • Integrates with ASP.NET Core authentication and authorization.

  • Simplifies development by abstracting complex networking details.

  • Scales with cloud services such as Azure SignalR Service.

  • Supports multiple client platforms, including web, mobile, and desktop.


Limitations of SignalR

  • Maintaining persistent connections increases server resource usage.

  • Applications with a very large number of concurrent users may require additional scaling strategies.

  • Network interruptions can temporarily disconnect clients, requiring reconnection logic.

  • Large message payloads can affect performance and should be minimized.

  • Real-time features add complexity to application design and testing.


Best Practices

  • Use WebSockets whenever possible for optimal performance.

  • Keep message payloads small to reduce bandwidth usage.

  • Secure Hubs with authentication and authorization.

  • Use groups to target messages efficiently instead of broadcasting to all clients.

  • Handle reconnection events gracefully on the client side.

  • Log connection events for monitoring and troubleshooting.

  • Offload large-scale real-time workloads to Azure SignalR Service or similar managed services when needed.

  • Validate incoming data to prevent malicious or invalid messages.


Conclusion

SignalR is a powerful framework in ASP.NET Core that enables real-time communication between servers and clients. By maintaining persistent connections and automatically selecting the best transport protocol, it allows developers to create highly interactive applications with instant updates. Whether building chat systems, live dashboards, collaborative tools, online games, or notification services, SignalR simplifies the implementation of real-time functionality while offering scalability, flexibility, and seamless integration with the ASP.NET Core ecosystem.