HomeContact

Building Real-Time Applications with SignalR and .NET 7 A Step-by-Step Guide

By Shady Nagy
Published in dotnet
April 22, 2023
3 min read
Building Real-Time Applications with SignalR and .NET 7 A Step-by-Step Guide

Table Of Contents

01
Introduction
02
Prerequisites
03
Step 1: Create a new ASP.NET Core Web Application
04
Step 2: Install SignalR package
05
Step 3: Add SignalR to Startup.cs
06
Step 4: Create a ChatHub class
07
Step 5: Create the chat client
08
Step 6: Create the HTML UI
09
Step 7: Run the application
10
Step 8: Create Unit Tests for the Chat Application
11
Further Reading
12
Conclusion
13
Feedback and Questions

Introduction

In today’s world, real-time applications are increasingly important to provide users with the most up-to-date and interactive experiences. SignalR is a powerful library that simplifies the process of adding real-time functionality to your applications. In this tutorial, we will walk you through the process of building a real-time chat application using SignalR and .NET 7.

Prerequisites

  • Basic knowledge of C# and ASP.NET Core
  • Visual Studio 2022 or later
  • .NET 7 SDK installed

Step 1: Create a new ASP.NET Core Web Application

  1. Open Visual Studio and click on “Create a new project.”
  2. Select “ASP.NET Core Web Application” and click “Next.”
  3. Name your project “SignalRChatApp” and click “Create.”
  4. Choose “Empty” template and ensure “ASP.NET Core 7.0” is selected. Click “Create.”

Step 2: Install SignalR package

  1. Right-click on your project in the Solution Explorer, and select “Manage NuGet Packages.”
  2. Search for “Microsoft.AspNetCore.SignalR” and install the latest version.

Step 3: Add SignalR to Startup.cs

  1. Open Startup.cs file.
  2. In the “ConfigureServices” method, add the following code to register SignalR:
services.AddSignalR();
  1. In the “Configure” method, add the following code to map SignalR hubs:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});

Step 4: Create a ChatHub class

  1. In the project, create a new folder called “Hubs.”
  2. Inside the Hubs folder, create a new class called “ChatHub” and inherit from “Hub” class.
  3. Add the following method to “ChatHub”:
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}

Step 5: Create the chat client

  1. In the “wwwroot” folder, create a new folder called “js.”
  2. Inside the “js” folder, create a new JavaScript file called “chat.js.”
  3. Add the following code to “chat.js”:
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = user + ": " + message;
var 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) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});

Step 6: Create the HTML UI

  1. In the “wwwroot” folder, create a new HTML file called “index.html.”
  2. Add the following code to “index.html”:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>SignalR Chat App</title>
</head>
<body>
<h1>SignalR Chat App</h1>
<ul id="messagesList"></ul>
<form>
<input type="text" id="userInput" placeholder="User" />
<input type="text" id="messageInput" placeholder="Message" />
<button type="submit" id="sendButton">Send</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.10/signalr.min.js"></script>
<script src="js/chat.js"></script>
</body>
</html>

Step 7: Run the application

  1. Press F5 or click the “Run” button in Visual Studio to start the application.
  2. Open a web browser and navigate to “http://localhost:[port]/index.html” (replace [port] with the actual port number).
  3. Open another browser window or tab and navigate to the same URL.
  4. Start chatting between the two browser instances and observe real-time message updates.

Step 8: Create Unit Tests for the Chat Application

To ensure that our chat application works as expected, let’s create unit tests for the ChatHub class.

  1. In the Solution Explorer, right-click the solution and select “Add” -> “New Project.”

  2. Choose “xUnit Test Project (.NET Core)” and click “Next.”

  3. Name the project “SignalRChatApp.Tests” and click “Create.”

  4. Install necessary NuGet packages:

    a. Right-click on the “SignalRChatApp.Tests” project and select “Manage NuGet Packages.” b. Search for “Microsoft.AspNetCore.SignalR” and install the latest version. c. Search for “Microsoft.AspNetCore.TestHost” and install the latest version. d. Search for “Moq” and install the latest version.

  5. Create a new class called “ChatHubTests” in the “SignalRChatApp.Tests” project.

  6. Add the following using statements at the top of the “ChatHubTests” class:

using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Moq;
using SignalRChatApp.Hubs;
using Xunit;
  1. Create a test method to verify the “SendMessage” functionality:
public class ChatHubTests
{
[Fact]
public async Task SendMessage_BroadcastsMessageToAllClients()
{
// Arrange
var mockClients = new Mock<IHubCallerClients>();
var mockClientProxy = new Mock<IClientProxy>();
mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);
var chatHub = new ChatHub { Clients = mockClients.Object };
var user = "TestUser";
var message = "TestMessage";
// Act
await chatHub.SendMessage(user, message);
// Assert
mockClients.Verify(clients => clients.All, Times.Once);
mockClientProxy.Verify(
clientProxy => clientProxy.SendCoreAsync(
"ReceiveMessage",
It.Is<object[]>(args => args[0].Equals(user) && args[1].Equals(message)),
default
),
Times.Once
);
}
}
  1. Run the tests:

    a. Open the Test Explorer by clicking on “Test” -> “Test Explorer” in the menu bar. b. Click on “Run All Tests” in the Test Explorer.

You should now see your test pass, ensuring that the “SendMessage” method in the ChatHub class correctly broadcasts the message to all connected clients.

Further Reading

To dive deeper into the topics covered in this post, consider checking out the following resources:

  1. SignalR Official Documentation - Dive deeper into the SignalR library by exploring the official documentation, which provides comprehensive guides and examples for various real-time scenarios.
  2. Unit Testing in .NET - Learn more about unit testing in .NET and how to create effective tests for your applications.
  3. ASP.NET Core - Get started with ASP.NET Core and learn how to build powerful web applications using the latest technologies and tools from Microsoft.
  4. .NET 7 - Discover the latest features and improvements in .NET 7, and learn how to leverage them in your projects.
  5. Visual Studio 2022 - Explore the latest version of Visual Studio and learn how to make the most of its features for efficient and productive development.

Conclusion

In this tutorial, we built a real-time chat application using SignalR and .NET 7 and added unit tests to verify the functionality. This foundation allows you to explore other real-time application possibilities while maintaining high-quality code through testing. SignalR is an excellent tool for enhancing your applications and providing users with a seamless and interactive experience.

Feedback and Questions

We’d love to hear your feedback on this tutorial! If you have any questions or suggestions for improvement, please don’t hesitate to reach out. You can leave a comment below, or you can contact us through the following channels:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

We’ll do our best to address any questions or concerns you may have. We look forward to hearing from you and helping you make the most of building real-time applications with SignalR in .NET 7!


Tags

#.NET7#SignalR#RealTimeApplications#ChatApplication#ASPNETCore#UnitTesting#CSharp#VisualStudio2022#CrossPlatform#Microsoft

Share


Previous Article
.NET 7 and Machine Learning with ML.NET Unleashing the Power of AI in Your Applications
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

AI
Angular
dotnet
GatsbyJS
Github
Linux
MS SQL
Oracle

Related Posts

Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
July 03, 2024
4 min

Quick Links

Contact Us

Social Media