DEV Community

Cover image for STEP-BY-STEP GUIDE TO IMPLEMENT SIGNALR WITH WEBSOCKETS IN ASP.NET CORE
Sapana Pal
Sapana Pal

Posted on • Edited on

STEP-BY-STEP GUIDE TO IMPLEMENT SIGNALR WITH WEBSOCKETS IN ASP.NET CORE

Unlocking Real-Time Web Apps: Mastering SignalR & WebSockets

SignalR is a library for ASP.NET Core that simplifies real-time communication between server and client. It automatically leverages WebSockets when available for optimal performance. Follow this comprehensive guide to integrate SignalR with WebSockets into your ASP.NET Core application.


1. Prerequisites

  • Visual Studio 2022 or later
  • .NET Core SDK (3.1, 5.0, 6.0, or later)
  • Basic knowledge of ASP.NET Core and JavaScript

2. Create a New ASP.NET Core Project

  1. Open Visual Studio
  2. Select Create a new project
  3. Choose ASP.NET Core Web Application
  4. Name your project and click Create
  5. Select ASP.NET Core Web App (Model-View-Controller) or Empty template based on your preference
  6. Ensure Enable Docker Support is unchecked unless needed
  7. Pick the latest .NET version and click Create

3. Add SignalR NuGet Package

  • Right-click on your project in Solution Explorer
  • Select Manage NuGet Packages
  • Search for Microsoft.AspNetCore.SignalR
  • Install the package

4. Configure SignalR in Startup.cs or Program.cs

For .NET 5 or earlier (Startup.cs):

public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // Add SignalR service services.AddSignalR(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // existing middleware... app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // Map SignalR hub endpoints.MapHub<MyHub>("/myHub"); }); } 
Enter fullscreen mode Exit fullscreen mode

For .NET 6+ (Program.cs):

var builder = WebApplication.CreateBuilder(args); // Add services builder.Services.AddControllersWithViews(); builder.Services.AddSignalR(); var app = builder.Build(); app.UseRouting(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // Map SignalR Hub app.MapHub<MyHub>("/myHub"); app.Run(); 
Enter fullscreen mode Exit fullscreen mode

5. Create the SignalR Hub Class

Create a new class MyHub.cs:

using Microsoft.AspNetCore.SignalR; public class MyHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } 
Enter fullscreen mode Exit fullscreen mode

This hub enables broadcasting messages to all connected clients.


6. Create Client Side (HTML + JavaScript)

In your Index.cshtml or similar view:

<!DOCTYPE html> <html> <head> <title>SignalR WebSocket Demo</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js"></script> </head> <body> <h1>SignalR WebSocket Demo</h1> <input type="text" id="userInput" placeholder="Your name" /> <input type="text" id="messageInput" placeholder="Message" /> <button id="sendButton">Send</button> <ul id="messagesList"></ul> <script> // Create connection const connection = new signalR.HubConnectionBuilder() .withUrl("/myHub") .withAutomaticReconnect() .build(); // Start connection connection.start().then(() => { console.log("Connected to SignalR hub"); }).catch(err => { console.error(err.toString()); }); // Receive message connection.on("ReceiveMessage", (user, message) => { const li = document.createElement("li"); li.textContent = `${user}: ${message}`; document.getElementById("messagesList").appendChild(li); }); // Send message document.getElementById("sendButton").addEventListener("click", () => { const user = document.getElementById("userInput").value; const message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(err => { console.error(err.toString()); }); }); </script> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

7. Enable WebSockets in Server Configuration

  • WebSockets are used automatically when supported.
  • Ensure WebSockets are enabled in your hosting environment:
    • IIS, Azure, or other hosting providers should have WebSocket support turned on.
    • In launchSettings.json or IIS config, verify WebSockets support.

8. Run Your Application

  • Press F5 or Ctrl + F5.
  • Open multiple browser windows.
  • Send messages from one window and observe real-time updates across all.

9. Additional Tips

  • Automatic fallback: SignalR automatically switches to Server-Sent Events or Long Polling if WebSockets aren’t available.
  • Explicit WebSocket usage: To force WebSockets only:
.withUrl("/myHub", { transport: signalR.HttpTransportType.WebSockets }) 
Enter fullscreen mode Exit fullscreen mode
  • Security: Always use HTTPS and implement authentication as needed.

Summary

  • Install the SignalR package
  • Configure services and endpoints
  • Create a Hub class
  • Connect from the client using JavaScript
  • Send and receive messages in real-time

Note: WebSockets are used automatically when available, providing fast, efficient real-time communication.


Top comments (0)