NashTech Blog

Building Real -Time web Application with SignalR and .NET

Table of Contents
woman, hacker, security-8119716.jpg

Introduction

Real-time web applications are becoming increasingly popular as they provide instant updates to users without the need for refreshing the page. It enables server-side code to push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data. SignalR is a library for ASP.NET that allows developers to add real-time web functionality to their applications.

Building a Real-Time Application with ASP.NET Core SignalR

Project Structure

Step 1: Setting Up the Project

First, let’s set up a new ASP.NET Core project.

  • Open Visual Studio and create a new ASP.NET Core Web Application.
  • Choose the “Web Application (Model-View-Controller)” template.
  • Name your project and click “Create”.

Step 2: Installing SignalR

To add SignalR to your project, you need to install the SignalR package.

  • Open the NuGet Package Manager Console (Tools > NuGet Package Manager > Package Manager Console).
  • Run the following command:
    Install-Package Microsoft.AspNetCore.SignalR

Step 3: Creating the SignalR Hub

The hub is the core component in SignalR that handles communication between the server and clients.

  1. Create a new folder named Hubs in your project.
  2. Add a new class named ChatHub in the Hubs folder:

    using Microsoft.AspNetCore.SignalR;
    using System.Threading.Tasks; 
    
    namespace SignalR.Hubs
    {
        public class ChatHub : Hub
        {
            public async Task SendMessage(string user, string message)
            {
                 await Clients.All.SendAsync("ReceiveMessage", user, message);
            }
        }
    }

Step 4: Adding SignalR to Program.cs file

Now, configure SignalR in your application startup.

    1. Open Program.cs. And add the following using statement at the top:
      using SignalR.Hubs;
    2. Update the ConfigureServices method to add SignalR services:
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllersWithViews();
          services.AddSignalR();
      }
    3. Update the Configure method to map the SignalR hub:
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Home/Error");
              app.UseHsts();
          }
          app.UseHttpsRedirection();
          app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>
          {
              endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Home}/{action=Index}/{id?}");
                  endpoints.MapHub<ChatHub>("/chatHub");
          });
      }

Step 5: Creating the Client-Side

Now, let’s create the client-side code to interact with the SignalR hub.

  1. Open Views/Home/Index.cshtml.
  2. Replace the existing content with the following code:
    @page
    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div id="messagesList"></div>
                <input type="text" id="userInput" placeholder="Name" />
                <input type="text" id="messageInput" placeholder="Message" />
                <button id="sendButton">Send</button>
            </div>
        </div>
    </div> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.3/signalr.min.js"></script> 
    <script type="text/javascript"> 
        const connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
        connection.on("ReceiveMessage", function (user, message) 
            { 
                const msg = user + " says " + message; 
                const li = document.createElement("li"); 
                li.textContent = msg; 
        document.getElementById("messagesList").appendChild(li); });
        
        connection.start().catch(function (err) 
        { 
            return console.error(err.toString()); 
        }); 
        document.getElementById("sendButton").addEventListener("click", function (event) 
        { 
            const user = document.getElementById("userInput").value; 
            const message = document.getElementById("messageInput").value; 
            connection.invoke("SendMessage", user, message).catch(function (err) 
            { 
                return console.error(err.toString()); 
            }); 
        event.preventDefault(); 
        });
    </script>

Step 6: Running the Application

Now that everything is set up, let’s run the application.

  1. Build and run your project (Ctrl+F5).
  2. Open the application in multiple browser windows or tabs.
  3. Enter a name and a message, then click “Send”.
  4. You should see the messages appearing in real-time across all open windows or tabs.

Output: App opened in multiple browsers.

Conclusion

We have successfully built a real-time web application using SignalR and .NET. This basic example demonstrates how to set up a SignalR hub, configure it in your ASP.NET Core application, and create a client-side script to send and receive messages in real-time. From here, you can extend the application to add more features such as user authentication, private messaging, and more. By leveraging SignalR, you can provide a seamless and interactive user experience in your web applications, making them more dynamic and responsive to user actions.

For more information you can refer my below blog

  1. Introduction to SignalR
  2. Advanced SignalR Techniques in .NET: Scalability, Performance and Custom Protocols
Picture of akshaychirde

akshaychirde

Leave a Comment

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

Suggested Article

Scroll to Top