Want to build a real-time chat app or push live notifications? In this blog, I’ll walk you through setting up SignalR from scratch using ASP.NET Core and a .NET console client. Perfect for beginners or those revisiting SignalR.
🔧 Step 1: Create the SignalR Server Project
Create an ASP.NET Core Web API project and add package
dotnet add package Microsoft.AspNetCore.SignalR
🧠 Step 2: Create a SignalR Hub
Create a new class ChatHub.cs
inside the project:
using Microsoft.AspNetCore.SignalR;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
🌐 Step 3: Configure the SignalR Hub in Program.cs
Update Program.cs
to register the SignalR service and endpoint:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// Add this line to map the hub
app.MapHub<ChatHub>("/chatHub");
app.Run();
🧪 Step 4: Run the Server
dotnet run
📥 Step 5: Create a .NET Console Client
Create a new console app and add SignalR client package
dotnet add package Microsoft.AspNetCore.SignalR.Client
🧑💻 Step 6: Build the Client Logic
Replace Program.cs
content with:
using Microsoft.AspNetCore.SignalR.Client;
var connection = new HubConnectionBuilder()
.WithUrl("https://<your localhost>/chatHub") your server
.WithAutomaticReconnect()
.Build();
// Receive messages
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
Console.WriteLine($"{user}: {message}");
});
try
{
await connection.StartAsync();
Console.WriteLine("Connected to SignalR Hub.");
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
return;
}
// Sending messages
while (true)
{
Console.Write("Enter your name: ");
var user = Console.ReadLine();
Console.Write("Enter your message: ");
var message = Console.ReadLine();
try
{
await connection.InvokeAsync("SendMessage", user, message);
}
catch (Exception ex)
{
Console.WriteLine($"Error sending message: {ex.Message}");
}
}
✅ Step 7: Test the Communication
- Run the server project:
cd ../SignalRServer
dotnet run
- Run the client project in a new terminal:
cd ../SignalRClient
dotnet run
Type your name and message in the console. If everything is set up correctly, you’ll see the message echoed back from the hub.
🧪 Test Multiple Clients
Open two terminals and run the client in each. You’ll see real-time communication between both.
Top comments (0)