DEV Community

Dominic Pascasio
Dominic Pascasio

Posted on • Updated on

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);
    var app = builder.Build();
  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>
            <input id='usernameInput' placeholder='username' />
            <input id='messageInput' placeholder='message' />
            <button id='sendButton'>Send</button>
            <ul id='conversationList'></ul>
            <script src=''></script>
            <script src='/chat.js'></script>
  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");
    // 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());
  6. Run the app using dotnet run and go to https://localhost:<port>/chat.html.

Microsoft Docs

Top comments (0)