net-core
  1. net-core-building-a-chat-app

Building a Chat App with ASP.NET Core WebSockets and SignalR

Building a real-time chat application can be challenging, but ASP.NET Core WebSockets and SignalR make it simple and efficient. In this page, we will discuss how to build a chat application using these technologies.

Overview

The application we will build is a simple chat application that allows users to communicate with each other in real-time. Users will be able to create a new chat room, select a chat room, and start chatting with other users in the room.

Components Required

  • Visual Studio or Visual Studio Code
  • .NET Core 3.1 or greater

Create a new ASP.NET Core project

Create a new ASP.NET Core Web Application project using Visual Studio or Visual Studio Code. Choose the ASP.NET Core Web Application project template. Name the project ChatApp.

Add SignalR to the project

To add SignalR to your project, follow these steps:

  1. Open the ChatApp.csproj file.
  2. Add the following package reference to the file:
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
</ItemGroup>
  1. Save the file and restore the packages.

Create a new chat hub

To create a new chat hub, follow these steps:

  1. Add a new empty C# class file to the Hubs folder.
  2. Name the file ChatHub.cs.
  3. Add the following code to the file:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

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

The SendMessage method sends a message to all clients in the chat room. The Clients.All.SendAsync method sends the message to all clients that are connected to the hub.

Create a new chat page

To create a new chat page, follow these steps:

  1. Add a new Razor Page to the Pages folder.
  2. Name the page Chat.cshtml.
  3. Add the following code to the file:
@page "/chat"
@using Microsoft.AspNetCore.SignalR.Client
@using System.Threading.Tasks

<h1>Chat</h1>

<div>
    <div><input id="userInput" placeholder="User name"></div>
    <div><textarea id="messageInput" placeholder="Message"></textarea></div>
    <div><button id="sendButton" disabled>Send</button></div>
</div>

<ul id="messageList"></ul>

<script>
    var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();

    connection.start().then(function () {
        document.getElementById("sendButton").disabled = false;
    }).catch(function (err) {
        return console.error(err.toString());
    });

    connection.on("ReceiveMessage", function (user, message) {
        var messageItem = document.createElement("li");
        messageItem.textContent = user + " says: " + message;
        document.getElementById("messageList").appendChild(messageItem);
    });

    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();
    });
</script>

This code sets up a SignalR connection to the ChatHub and provides an input field for the user to enter a message and a button to send the message.

Test the chat app

To test the chat app, start the application and navigate to the Chat page. In multiple browser windows, enter a user name and start chatting in real-time.

Summary

In this page, we discussed how to build a chat application using ASP.NET Core WebSockets and SignalR. We built a simple chat app that allows users to communicate with each other in real-time. By following the outlined steps, you can create your own real-time chat application with ease.

Published on: