Building a Real-Time Chat Application in .NET Core with SignalR and React

Building a Real-Time Chat Application in .NET Core with SignalR and React

Learn how to build a real-time messaging app using SignalR in .NET Core and React for seamless communication between clients.

Building a Real-Time Chat Application in .NET Core with SignalR and React

Introduction

In this blog post, we’ll build a real-time chat application using SignalR in .NET Core and React. SignalR is a powerful library that facilitates real-time web functionality, such as push notifications and live updates. By integrating SignalR with React, we can build a responsive, interactive, and highly functional chat application.

SignalR abstracts the complexities of working with WebSockets, long polling, and other technologies used for real-time communication, making it easy for developers to integrate real-time features into their applications.

Prerequisites

  • Basic knowledge of .NET Core and React.
  • Visual Studio or any code editor.
  • Node.js and npm installed.
  • Postman or another API testing tool (optional).

If you're new to .NET Core or React, I recommend checking out some basic tutorials first. In this post, we'll focus on the integration of these two technologies using SignalR.

Setting Up the Backend with .NET Core and SignalR

We will first create a .NET Core Web API project and set up SignalR for real-time communication. Let’s get started by creating a new project.

  1. Create a new Web API project using the following command:
    dotnet new webapi -n SignalRChatApp
  2. Navigate to the project folder:
    cd SignalRChatApp
  3. Install the necessary SignalR NuGet package:
    dotnet add package Microsoft.AspNetCore.SignalR

Now, let's configure SignalR in the Startup.cs file:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

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

Here we added SignalR using services.AddSignalR() and defined an endpoint /chathub for the chat hub. Next, we’ll implement the hub itself.

Create a new folder Hubs and add a class called ChatHub.cs to manage real-time communication:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

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

In the ChatHub class, we define a method SendMessage that sends messages to all connected clients in real time. The method takes the user and message parameters and broadcasts them to all connected clients using the Clients.All.SendAsync method.

Frontend Setup with React

Next, we’ll set up the React frontend to communicate with the SignalR backend. Start by creating a new React application using the following command:

npx create-react-app chat-app

After the app is created, navigate to the project folder:

cd chat-app

Now, install the SignalR client package:

npm install @microsoft/signalr

Let's now set up the SignalR connection in the App.js file:

import React, { useState, useEffect } from 'react';
import './App.css';
import { HubConnectionBuilder } from '@microsoft/signalr';

function App() {
  const [connection, setConnection] = useState(null);
  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const newConnection = new HubConnectionBuilder()
      .withUrl("https://localhost:5001/chathub")
      .build();

    setConnection(newConnection);
  }, []);

  const sendMessage = async () => {
    if (connection.connectionStarted) {
      try {
        await connection.send("SendMessage", "User", message);
        setMessage("");
      } catch (error) {
        console.error("Error sending message:", error);
      }
    } else {
      console.log("No connection.");
    }
  };

  useEffect(() => {
    if (connection) {
      connection.on("ReceiveMessage", (user, message) => {
        setMessages(messages => [...messages, `${user}: ${message}`]);
      });

      connection.start().catch(error => console.error("Error starting connection:", error));
    }
  }, [connection]);

  return (
    <div className="App">
      <h1>Real-Time Chat App</h1>
      <div>
        <ul>
          {messages.map((msg, index) => <li key={index}>{msg}</li>)}
        </ul>
        <input type="text" value={message} onChange={e => setMessage(e.target.value)} />
        <button onClick={sendMessage}>Send</button>
      </div>
    </div>
  );
}

export default App;
            

Here we use the HubConnectionBuilder to connect to the SignalR hub on the backend and send messages using the send method. We also listen for incoming messages with on and update the UI with the new messages in real time.

Running the Application

To run the application, follow these steps:

  • Start the backend .NET Core Web API using the following command:
    dotnet run
  • Start the React frontend using:
    npm start

Your real-time chat application is now up and running! Open the React app in your browser, and you can send and receive messages in real time.

Conclusion

In this blog post, we’ve built a real-time chat application using SignalR in .NET Core and React. SignalR makes it easy to implement real-time communication in web applications, and React's component-based architecture makes it a great fit for building interactive UIs. We’ve set up a SignalR hub on the backend, created a frontend with React, and connected them to provide real-time chat functionality.

With this foundation, you can extend the application by adding user authentication, storing messages in a database, or adding more advanced features like notifications and private messaging. Happy coding!

© 2025 Sandeep Mhaske. All rights reserved.

Follow me on LinkedIn | GitHub

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post