SignalR
Introduction
SignalR is a library for ASP.NET that simplifies the process of adding real-time web functionality to applications. Real-time web functionality enables server-side code to push content to clients instantly.
Setting Up the Development Environment
Before you start, ensure you have the following installed:
- Visual Studio 2019 or later
- .NET Core SDK
Example: Installing .NET Core SDK
https://dotnet.microsoft.com/download/dotnet-core
Creating a New SignalR Project
Open Visual Studio and create a new project:
- Select "Create a new project".
- Choose "ASP.NET Core Web Application" and click "Next".
- Name your project and select the location to save it. Click "Create".
- In the "Create a new ASP.NET Core Web Application" dialog, select "Web Application" and click "Create".
Adding SignalR to the Project
To use SignalR, you need to add the SignalR library to your project. Open the Startup.cs
file and modify it to include SignalR:
Example: Adding SignalR to Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub("/chatHub");
});
}
Creating the SignalR Hub
Next, create a Hub class. The Hub is responsible for handling client-server communication. Add a new class named ChatHub.cs
in the project:
Example: ChatHub Class
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Creating the Client-Side Code
To communicate with the SignalR server, you need to create some client-side code. Add the following code to the wwwroot/index.html
file:
Example: Client-Side Code
<!DOCTYPE html>
<html>
<head>
<title>SignalR Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.3/signalr.min.js"></script>
</head>
<body>
<div>
<input type="text" id="userInput" placeholder="Name" />
<input type="text" id="messageInput" placeholder="Message" />
<button onclick="sendMessage()">Send</button>
</div>
<ul id="messagesList"></ul>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user}: ${message}`;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(err => console.error(err.toString()));
function sendMessage() {
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>
Running the Application
Run the application by pressing F5
or clicking the "Run" button in Visual Studio. Navigate to https://localhost:5001/
to see the chat application in action. You can open multiple browser windows to see the real-time updates as messages are sent.
Conclusion
Congratulations! You have created a simple chat application using SignalR and ASP.NET Core. This tutorial covered the basics of setting up a new project, adding SignalR, creating a Hub, writing client-side code, and running the application. From here, you can extend the application with more features and integrate it with a backend service.