Member-only story
Real-time communication with SignalR in .NET Core
Introduction: In today’s world, real-time communication is essential for many web applications. For example, consider an online game where players need to communicate with each other in real-time, or a chat application where users expect instant messaging. Fortunately, SignalR, a real-time web framework, is available to help developers implement such functionalities in their web applications.
In this blog, we will explore how to use SignalR in .NET Core to implement real-time communication. We will create a simple chat application where users can send and receive messages in real-time. Let’s get started!
Step 1: Create a new .NET Core project
Open Visual Studio and create a new .NET Core project. Select “ASP.NET Core Web Application” and give your project a name. Choose the “API” template and click “Create”.
Step 2: Install the SignalR package
Next, we need to install the SignalR package in our project. Open the NuGet Package Manager and search for “Microsoft.AspNetCore.SignalR”. Install the latest version of the package.
Step 3: Add a SignalR hub
A SignalR hub is a class that manages real-time communication between clients and the server. We need to create a new hub for our chat application.
Create a new folder called “Hubs” in your project and add a new class called “ChatHub.cs”. This class will inherit from the “Hub” class provided by the SignalR package.
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace YourProjectName.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
This code defines a method called “SendMessage” that takes two parameters: the name of the user who sent the message and the message itself. It then calls the “SendAsync” method to send the message to all connected clients, passing in the name of the method (“ReceiveMessage”) and the parameters to be sent.
Step 4: Configure SignalR in the Startup class
In the Startup class, we need to add SignalR to the application’s services and middleware.