ASP.NET Core - Tiny Chat App using SignalR

kazinix

Dominic Pascasio

Posted on September 2, 2022

ASP.NET Core - Tiny Chat App using SignalR

Warning! This code is for demonstration purposes only.

  1. Create an empty ASP.NET web app:

    dotnet new web -o TinyChat
    
  2. In your Program.cs, add SignalR service, set to serve static files and map the SignalR hub.

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSignalR();
    var app = builder.Build();
    
    app.UseStaticFiles();
    app.MapHub<ChatHub>("/ChatHub");
    app.Run();
    
  3. In your project directory, add ChatHub.cs that contains:

    using Microsoft.AspNetCore.SignalR;
    
    public class ChatHub : Hub
    {
        // this can be invoked from the client -- web browser in our example
        public async Task SendMessage(string username, string message)
        {
            // invoke ReceiveMessage on all clients connected
            await Clients.All.SendAsync("ReceiveMessage", username, message);
        }
    }
    
  4. Add folder wwwroot in the project directory. Then add chat.html which contains:

    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <input id='usernameInput' placeholder='username' />
            <input id='messageInput' placeholder='message' />
            <button id='sendButton'>Send</button>
            <ul id='conversationList'></ul>
            <script src='https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.8/signalr.min.js'></script>
            <script src='/chat.js'></script>
        </body>
    </html>
    
  5. In wwwroot, add chat.js which contains:

    "use strict";
    document.addEventListener('DOMContentLoaded', function() {
    var connection = new signalR.HubConnectionBuilder().withUrl("/ChatHub").build();
    
    // Handler for receiving a message. This will be invoked by the server.
    connection.on("ReceiveMessage", function (username, message) {
        var messageItem = document.createElement("li");
        messageItem.textContent = `${username}: ${message}`; 
    
        var conversationList = document.querySelector("#conversationList");
        conversationList.prepend(messageItem);
    });
    
    // Initiate connection and set callback for error.
    connection.start().then(function () {
    
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    // Handler for sending message to the server.
    document.querySelector("#sendButton").addEventListener("click", function (event) {
        var username = document.querySelector("#usernameInput").value;
        var message = document.querySelector("#messageInput").value;
    
        connection.invoke("SendMessage", username, message)
        .catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    });
    
  6. Run the app using dotnet run and go to https://localhost:<port>/chat.html.

Resource
Microsoft Docs

💖 💪 🙅 🚩
kazinix
Dominic Pascasio

Posted on September 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related