write a signalr chat app in csharp

To write a SignalR Chat App in C# follow the below steps:

Step 1: Create a new ASP.NET Core project

Create a new ASP.NET Core Web Application project in Visual Studio. Choose the ASP.NET Core Web Application template and select the Web Application (Model-View-Controller) option. Name the project "SignalRChatApp" and click Create.

Step 2: Install SignalR package

Install the Microsoft.AspNetCore.SignalR package using NuGet Package Manager.

Step 3: Add SignalR hub

Add a SignalR hub class to the project. A hub is a high-level pipeline that allows the client and server to communicate over a variety of transport protocols used in SignalR.

Create a new SignalR Hub class called "ChatHub.cs" inside the "Hubs" folder. Add the using statements for SignalR namespace and Microsoft.AspNetCore.SignalR package.

main.cs
using Microsoft.AspNetCore.SignalR;

namespace SignalRChatApp.Hubs
{
    public class ChatHub : Hub
    {
    }
}
114 chars
9 lines

Step 4: Configure SignalR in startup.cs

Add the services and middleware required to use SignalR in the Startup.cs file.

On the ConfigureServices method add the following:

main.cs
services.AddSignalR();
23 chars
2 lines

On the Configure method add the following:

main.cs
app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("/chathub");
});
71 chars
5 lines

Step 5: Add Chat UI

Create a Chat View for the application. Right Click on the "Views" folder, select Add, then View. Name this view "Chat". Add HTML markup for creating the chat window.

Step 6: Add SignalR client code

In the Chat view, add the SignalR client library code in the header section of the view.

main.cs
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
62 chars
2 lines

Add the SignalR client code in a script section at the bottom of the view.

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

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

    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>
802 chars
21 lines

Step 7: Implement SignalR server code

Implement the server-side method of the SignalR Hub.

In the ChatHub.cs file add the following code:

main.cs
public async Task SendMessage(string user, string message)
{
    await Clients.All.SendAsync("ReceiveMessage", user, message);
}
129 chars
5 lines

This method sends a message from the client to all connected clients.

Step 8: Run the application

Run the application to see the chat window. Enter a name and message in the chat window and click the send button. You will see the message in the chat window.

This is a basic chat application using SignalR in C#. You can further enhance the chat functionality by adding features like user authentication, group chat, etc.

gistlibby LogSnag