Real-time web communication using SignalR in .NET Core

In modern web applications, users expect real-time updates without having to manually refresh the page. SignalR is a popular library that enables real-time web communication and allows developers to build real-time web applications. In this article, we will explore how to use SignalR in .NET Core to create real-time web communication between the server and client.

What is SignalR? SignalR is a library that provides real-time web communication for web applications. It enables real-time communication between the server and the client using WebSockets, Server-Sent Events (SSE), or long-polling. SignalR handles the connection management, allowing for seamless communication between the server and the client.

Setting up a SignalR project in .NET Core To get started, create a new .NET Core web application in Visual Studio. In the “Create a new project” dialog box, select “ASP.NET Core Web Application” and then select “SignalR” as the project template.

This will create a new SignalR project with some default code that we can modify to create a real-time web application.

Creating a real-time chat application To demonstrate how SignalR can be used for real-time web communication, we will create a real-time chat application. The application will allow users to connect to a chat room and send and receive messages in real time.

  1. Create a chat hub The first step is to create a chat hub. A hub is a class that serves as the main point of communication between the server and the client. In the “SignalR” folder, add a new class called “ChatHub” that inherits from “Hub”. This class will be responsible for handling real-time communication between the server and the client.
  2. Add methods to the chat hub In the “ChatHub” class, add two methods – one for sending messages and another for joining a chat room.
public class ChatHub : Hub
    public async Task SendMessage(string user, string message)
        await Clients.All.SendAsync("ReceiveMessage", user, message);

    public async Task JoinRoom(string roomName)
        await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
        await Clients.Group(roomName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has joined the room {roomName}.");

The “SendMessage” method sends a message to all clients connected to the chat room, and the “JoinRoom” method adds the user to the specified chat room and sends a message to all clients in the room.

  1. Modify the default code In the “Pages” folder, open the “Index.cshtml.cs” file, and modify the code to use the chat hub. Add the following code to the “OnGet” method:
public void OnGet()
    ViewData["Title"] = "Chat";
    ViewData["RoomName"] = "General";

    if (User.Identity.IsAuthenticated)
        ViewData["Username"] = User.Identity.Name;

    ViewData["Message"] = "Welcome to the chat room!";

    if (HttpContext.Request.Query.ContainsKey("room"))
        ViewData["RoomName"] = HttpContext.Request.Query["room"];

    ViewData["RoomName"] = ViewData["RoomName"].ToString().ToLowerInvariant();

    ViewData["Connections"] = _chatManager.GetConnectionsForRoom(ViewData["RoomName"].ToString());

    var user = User.Identity.Name ?? "Anonymous";
    _chatManager.AddConnection(Context.ConnectionId, ViewData["RoomName"].ToString(), user);

    // Connect to the chat hub
    _chatHubContext.Clients.All.SendAsync("JoinRoom", ViewData["RoomName"].ToString());

    // Receive messages from the chat

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories