Do you remember when you last refreshed the web page? It seems like a decade or so ago, right?
Now, the scenario is quite different. Businesses use web apps to keep users hooked on every action that occurs in real life.
For example, if you place a food order on a food delivery app,
Seconds ago, “Your order is accepted.”
Seconds ago, “The restaurant is preparing your order.”
Seconds ago, “The driver is assigned to deliver your order.”
Seconds ago, “The driver arrived at the restaurant and picked up your order.”
You receive constant updates about your food order, and you never hit the refresh button. According to User Guiding, 39% users do not interact with content that takes too long to load, meaning users nowadays expect real-time content without having to request.
Real-time applications empower industries like food delivery, stock trading, messaging, and live streaming, providing instant updates without manual refreshes. ASP.NET Core SignalR enables this seamless experience by enabling real-time messaging in ASP.NET Core without the complexity of managing low-level networking.
Leveraging SignalR WebSockets ensures low-latency communication and seamlessly falls back to other transport mechanisms when needed. This guide will explore building real-time apps with ASP.NET Core with SignalR and following best practices for scaling web applications to handle high traffic efficiently.
Understanding Real-Time Communication in Web Applications with ASP.NET Core SignalR
In today’s fast-paced world, nobody likes to wait. The already-existing real-time apps have made us want constant updates, whether we’re messaging a friend and seeing “typing” or “blue tick,” a driver heading to you for your daily commute through a ride-sharing app, or the constant price movement in any finance app, which helps us make informed decisions in trading.
We will explain everything step-by-step since there are many technological processes in the backend and front end.
To start with, let’s understand.
What Difference Do Real-time Web Applications Bring?
Unlike traditional web applications, which depend entirely on the response-request model, real-time web apps enable spontaneous data exchange between the app user and the server.
To enable prompt data exchange and respond without manually requesting, several technologies play a crucial role, such as WebSockets, Server-Sent Events, Long Polling, and HTTP Streaming.
All of the above technologies have pros and cons, but when compared with ASP.NET Core with SignalR, the latter wins the battle.
Feature
ASP.NET Core SignalR
WebSockets
Server-Sent Events (SSE)
Long Polling
HTTP Streaming
Full-Duplex Communication
✅
✅
❌
❌
❌
Automatic Transport Handling
✅
❌
❌
❌
❌
Ease of Use
✅
❌
✅
✅
✅
Performance & Efficiency
✅
✅
❌
❌
❌
Scalability
✅
✅
❌
❌
❌
Browser Support
✅
✅
❌
✅
✅
Mobile & Cross-Platform Support
✅
✅
❌
✅
❌
Fallback Mechanism
✅
❌
❌
❌
❌
Security Features
✅
✅
✅
✅
✅
Ideal Use Cases
Chat apps
Live dashboards
Multiplayer gaming
IoT
Real-time messaging
Interactive apps
Stock trading
News feeds
Live updates
Notifications
Simple applications with no WebSocket support
Live video/audio streaming
Social media feeds
To sum up, ASP.NET Core SignalR offers:
Automatic transport selection
Depending upon the network conditions and user-side capability, SignalR selects the transport (communication mechanism) to enable data exchange.
Development ease
SignalR provides a high-level API, eliminating the time-consuming process of manually handling WebSockets. This allows developers to focus on business logic.
Scalability
Worry no more with SignalR because it integrates with Azure SignalR service, Redis backplanes, and cloud deployments for enterprise-grade applications.
Cross-platform & multi-client support
Build mobile apps using Flutter and React Native seamlessly since it works amazingly well.
Security & authentication
SignalR seamlessly integrates with JWT for secure token-based authentication, which is widely used in single-page and mobile apps. Not only that, but it also even integrates with OAuth & OpenID connect for third-party authentication.
So, that’s how real-time apps built with ASP.NET Core SignalR bring the difference.
Setting Up SignalR in an ASP.NET Core Application
Step 1: Install SignalR
Run the following command to install SignalR in your .NET Core project:
dotnet add package Microsoft.AspNetCore.SignalR
Step 2: Create a SignalR Hub
A SignalR Hub is the central communication point where clients and servers exchange messages. Here’s an ASP.NET Core SignalR example for a chat hub:
public class ChatHub : Hub {
public async Task SendMessage(string user, string message) {
This configuration enables SignalR in .NET Core to handle real-time messaging in ASP.NET Core applications.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub("/chatHub");
});
app.Run();
Building a Simple Real-Time Application with SignalR
One of the most common use cases of ASP.NET Core SignalR is real-time application development. In this section, we’ll create a basic chat app where multiple users can send and receive messages instantly without refreshing the page.
Step 1: Set Up an ASP.NET Core Project
First, create a new ASP.NET Core Web API project in Visual Studio or using the .NET CLI:
public class ChatHub : Hub {
public async Task SendMessage(string user, string message) {
The SendMessage method receives messages from a client and sends them to all connected clients using Clients.All.SendAsync().
This enables broadcasting messages to multiple clients in real-time.
Step 3: Configure SignalR in ASP.NET Core
Modify the Program.cs file to register the SignalR hub and configure routing:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub("/chatHub"); });app.Run();
Explanation:
The MapHub(“/chatHub”) method maps the hub to the /chatHub endpoint.
Clients will use this endpoint to connect to the SignalR server.
Step 4: Create the Client-Side Code
For the front end, use JavaScript to interact with the SignalR hub. Add the SignalR JavaScript library via CDN in an index.html file:
Real-Time Chat
Real-Time Chat
Step 5: Run the Application
Start the ASP.NET Core application:
Open the index.html file in a browser.
Open the same file in multiple tabs or different devices.
Enter a username and a message, then click Send—the message should appear instantly on all open clients!
Advanced SignalR Features & Best Practices
There can be times when handling SignalR-backed web apps could be crucial since there would be scalability issues, security maintenance, and performance optimization. But with a few vital features, developers could develop scalable, secure, and resilient real-time web apps. We have mentioned the best practices that need to be followed to upgrade your SignalR real-time web apps.
Scaling SignalR with Redis for Multiple Servers
SignalR hubs were sufficient for small-scale applications since they store client connections in memory. Only when enterprise-grade web apps, especially ones with multiple servers, were introduced with scalability as a significant challenge did Redis backplane become a robust solution. Let us break down how scalability was possible with Redis:
Acting as a message broker, Redis enables SignalR servers to interact with each other.
Due to Redis, messages are broadcasted on every connected server to balance the load and enhance user experience (due to not letting them wait).
How to implement Redis:
Developers need to install Redis and Microsoft.AspNetCore.SignalR.StackExchangeRedis package.
Then, configure SignalR to use Redis as a backplane.
Finally, deploy across servers and keep an eye on maintaining inter-server communication.
Using Azure SignalR Service for Better Performance
Azure SignalR simplifies complex WebSockets connections and enables maintaining cloud-based apps. Here, developers can leverage Microsoft Azure to handle connection management, scaling, and performance optimization, which offloads handling the SignalR infrastructure manually.
Below are the benefits of Azure SignalR services:
Ensures real-time updates and regularly optimized for cloud environments
Reduces load from the SignalR traffic
Manages thousands of concurrent connections without requiring manpower
How to implement:
Developers need to create an Azure SignalR service for instance.
Post creating, configure AS.NET core app to leverage Azure SignalR service.
Lastly, modify our SignalR hub connection settings to divert traffic through Azure.
Handling Authentication & Security in SignalR Connection
SignalR in .NET core enables persistent user-server connection, which is quite vulnerable to data leaks, thefts, cyberattacks, and unauthorized access. Securing such connections is mandatory in real-time applications.
We have listed the following best practices to secure SignalR connections:
It is required to use authentication tokens by implementing JWT (JSON web tokens) or OAUTH to authenticate users before they login to SignalR hubs.
Another best practice that needs to be strictly followed is restricting access to hubs and allowing only authorized users, and that too using policies and claim-based authentications.
Ensure HTTPs has been used and enable SSL/TLS to secure real-time messaging.
Make sure to limit the exposure of hub methods and validate all the incoming data to prevent injection attacks from cyber attackers.
Error Handling & Reconnection Strategies in Real-Time Apps
Real-time apps are bound to be dependent on constant server connections, which means any network disruption or server restart would interrupt user experience. With proper error handling mechanisms and reconnection strategies, you can make the user experience memorable and leave the user to return to relive it.
In such a scenario, we follow these best practices for error handling and reconnecting in SignalR:
Configure the in-built automatic reconnection feature in SignalR
Implement reconnecting alternatives like a fallback to periodic API polling
Keep limited exponential backoff retries so as not to overwhelm the server with connection attempts
Keep using logging tools to track the record of client disconnects and SignalR failure
Conclusion
Creating real-time web apps that deliver instant updates is crucial for businesses looking to enhance user experience. ASP.NET Core SignalR makes it easy to develop interactive applications with real-time capabilities. Whether you’re working on real-time messaging, live notifications, or collaborative tools, SignalR ensures smooth data transmission. With its built-in support for SignalR WebSockets, applications remain fast and responsive, even under high traffic. To build real-time apps with ASP.NET Core SignalR, developers must focus on scalability, security, and performance optimizations.
To handle thousands of concurrent users, Azure SignalR Service and Redis scaling strategies ensure reliability and efficiency. Implementing authentication, authorization, and secure WebSocket connections keep user data protected. Error handling mechanisms and auto-reconnection strategies prevent disruptions in real-time interactions. By leveraging these best practices, developers can build high-performing real-time web apps that meet modern business needs.
Take your application to the next level and develop real-time features with ASP.NET Core SignalR today!
Author
SPEC INDIA
SPEC INDIA, as your single stop IT partner has been successfully implementing a bouquet of diverse solutions and services all over the globe, proving its mettle as an ISO 9001:2015 certified IT solutions organization. With efficient project management practices, international standards to comply, flexible engagement models and superior infrastructure, SPEC INDIA is a customer’s delight. Our skilled technical resources are apt at putting thoughts in a perspective by offering value-added reads for all.