Building Real-Time Applications with SignalR and ASP.NET Core
Real-time applications are becoming increasingly important in today’s interconnected world, enabling features such as live updates, notifications, and real-time collaboration. SignalR is a library for ASP.NET Core that facilitates adding real-time web functionality to applications. In this article, we will explore how to build real-time applications using SignalR and ASP.NET Core.
What is SignalR?
SignalR is an open-source library that simplifies the process of adding real-time web functionality to applications. It enables server-side code to push content to connected clients instantly, allowing for real-time updates and interactions.
Benefits of SignalR
- Real-Time Updates: Provides instant updates to clients without needing to refresh the page.
- Simplified Communication: Abstracts the complexity of different communication protocols, providing a unified API.
- Scalability: Can be scaled out using Azure SignalR Service or other backplanes.
- Supports Multiple Clients: Works with web browsers, mobile apps, and desktop applications.
Setting Up an ASP.NET Core Project
Let’s start by setting up an ASP.NET Core Web API project and adding SignalR support:
dotnet new webapi -n RealTimeApp
cd RealTimeApp
dotnet add package Microsoft.AspNetCore.SignalR
Creating a SignalR Hub
A hub is a central point in SignalR where client-server communication is managed. Let’s create a hub for our real-time application.
Hubs/ChatHub.cs
:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace RealTimeApp.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Configuring SignalR in ASP.NET Core
Next, configure SignalR in the ASP.NET Core application.
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<Hubs.ChatHub>("/chathub");
});
}
Creating a Client Application
Let’s create a simple client application to interact with our SignalR hub. We will use a basic HTML page with JavaScript to connect and send messages.
wwwroot/index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Chat</title>
</head>
<body>
<h1>Real-Time Chat</h1>
<input type="text" id="user" placeholder="Enter your name" />
<input type="text" id="message" placeholder="Enter a message" />
<button onclick="sendMessage()">Send</button>
<ul id="messagesList"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.7/signalr.min.js"></script>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user}: ${message}`;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(err => console.error(err.toString()));
function sendMessage() {
const user = document.getElementById("user").value;
const message = document.getElementById("message").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
}
</script>
</body>
</html>
Running the Application
Run the ASP.NET Core application and open the index.html
file in a web browser. Enter a username and message, then click “Send” to see real-time updates in the chat.
Conclusion
In this article, we explored how to build real-time applications using SignalR and ASP.NET Core. We created a simple chat application that demonstrates the power of real-time communication. SignalR abstracts the complexities of real-time communication protocols, making it easy to add real-time features to your applications. By following these steps, you can enhance your web applications with real-time capabilities, providing a more interactive and dynamic user experience.