Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

SignalR Tutorial

Introduction to SignalR

SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.

Setting Up the Environment

To get started with SignalR, you need to set up your development environment. This tutorial assumes you have Visual Studio installed.

Create a new ASP.NET Core Web Application and choose the "Web Application" template. Ensure "Configure for HTTPS" is checked.

Installing SignalR

Next, add the SignalR library to your project using NuGet Package Manager.

Install-Package Microsoft.AspNetCore.SignalR

Creating a SignalR Hub

A Hub is a class that serves as a high-level pipeline that handles client-server communication.


// Create a new class called "ChatHub" in the "Hubs" folder
using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
                

Configuring SignalR in Startup.cs

Configure SignalR middleware in the Startup class to enable SignalR services.


// Add services to the container in ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddSignalR();
}

// Configure the HTTP request pipeline in Configure method
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<ChatHub>("/chatHub");
    });
}
                

Creating the Client-Side

To connect to the SignalR Hub from the client side, you need to include the SignalR JavaScript client library and create a connection.


<!-- Add the SignalR client library in your HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.18/signalr.min.js"></script>

<!-- Create a connection and start it -->
<script>
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chatHub")
        .build();

    connection.start().catch(err => console.error(err.toString()));

    connection.on("ReceiveMessage", (user, message) => {
        const msg = user + ": " + message;
        const li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messagesList").appendChild(li);
    });

    document.getElementById("sendButton").addEventListener("click", event => {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;
        connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
        event.preventDefault();
    });
</script>
                

Example HTML

This is a basic example of how your HTML file might look with the SignalR client-side code embedded.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Application</title>
</head>
<body>
    <div>
        <input type="text" id="userInput" placeholder="Your name" />
        <input type="text" id="messageInput" placeholder="Your message" />
        <button id="sendButton">Send</button>
    </div>
    <ul id="messagesList"></ul>

    <!-- SignalR client library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.18/signalr.min.js"></script>

    <!-- SignalR client-side script -->
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        connection.start().catch(err => console.error(err.toString()));

        connection.on("ReceiveMessage", (user, message) => {
            const msg = user + ": " + message;
            const li = document.createElement("li");
            li.textContent = msg;
            document.getElementById("messagesList").appendChild(li);
        });

        document.getElementById("sendButton").addEventListener("click", event => {
            const user = document.getElementById("userInput").value;
            const message = document.getElementById("messageInput").value;
            connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
            event.preventDefault();
        });
    </script>
</body>
</html>
                

Testing the Application

Run the application in Visual Studio. Open multiple browser windows and navigate to the application URL. You should be able to send messages between the windows in real-time.

Conclusion

In this tutorial, we covered the basics of setting up and using SignalR in an ASP.NET Core application. SignalR provides a powerful and easy-to-use framework for adding real-time capabilities to your applications.