How to Create a Chat App with ASP.Net Core 3.1 (SignalR) and Angular 10

Real-time web functionality to applications for a better user experience

Udith Gayan Indrakantha
LinkIT
7 min readJul 24, 2020

--

Introduction

Nowadays, almost all the applications are expected to deliver up-to-date information to the end-users without hitting a refresh button. That is, we need a real-time connection with the servers to fetch information. With .NET frameworks, a framework called SignalR comes to enable real-time data transferring.

In my article, I use this SignalR to create a chat application with a combination of Angular 10 ( but the implementation is similar to Angular 9, 8,7, and 6 too) and ASP.NET Core. The diagram below shows an overview of my project.

Overview of the chat Process

Here, one user can send messages, and these messages are sent to the back-end through a POST request. When the server received the message via a controller method, the controller method calls a hub method. The hub method then sends the received message to all the clients who are listening to that hub through a web socket. We use the SignalR framework along with ASP.NET Core Web API to create a real-time socket connection with clients.

SignalR

SignalR is an open-source real-time framework with high performances. We can write hubs with C# language. This SignalR comes with client SDKs for JavaScript, C#, and Java. Therefore it is easy to integrate many applications using this SignalR real-time framework. Further, this can be used to deliver real-time and fast gaming experience, chat services, database update notifications, etc.

Let’s Create the App

First, create a new Asp.Net Core Web API project. I use Visual Studio 2019 for this purpose. The initial Project might look as below, with a file set in Solution Explorer right.

Initial Project view

In this project, there are two files that come with the initial creation for test purposes and are not required for our project. So please delete the following files highlighted in yellow. (one file is in Controllers folder).

Initial Project structure

Let’s start setting up the back end of the project.

Here in my backend, there is a controller class and a method that listens to a post request with the sender’s text message. When the method is invoked by a request, this method invokes another method in the hub that broadcasts the sender’s message to all clients listening to that hub created with SignalR.

First of All, let’s create a hub. Inside the project, create a new folder and name it as ‘Hubs’. Inside the ‘Hubs’ folder, add a new class file with the name as ‘ChatHub’. This class must inherit the abstract class ‘Hub’ from Microsoft.AspNetCore.SignalR. The final class file is as below.

Whenever this SendMessage1(….) method is called, it sends the parameters user and message to the client-side receiver with the name “ResceiveOne”. (We can add more parameters as well) . We are going to call this method from the controller class.

But before that, we have to enable SignalR service and define an endpoint that is used by clients to listen to this hub. Go to the Startup.cs file and add the lines marked with comments. (LineNo: 30, 50)

From the client, we send a post request containing an object composed of a username and the text message. So, creating a request for DTO class in the back-end is a good practice. Therefore, create a folder name ReqDto inside the project and add a class file named MessageDto as below.

Let’s create a controller class now. Go inside the Controllers folder and add a class file named ‘ChatController’ and make the file as below.

Here in the above code, if we need to use a hub from an external place, we can use the IHubContext interface after injecting it through the constructor. The hub sends the message to all the Clients and invokes a client function with a name similar to the one defined here as the first parameter ( “ReceiveOne” ) in SendAsync(….) method.

Add CORS Policies

Since the back-end and the front-end run on two different servers, we have to allow cors in the backend. To enable cors in the back-end, you need to add the lines squared in green to the startup.cs file as below. localhost:4201 is the server and port of my angular project. You can edit it according to yours.

Create the Angular App

First of all, create an Angular app using basic commands.

ng new web-chat-app

cd ./web-chat-app

You are now inside the angular app. This is my final Angular project structure.

Angular Project’s Structure

I have created a DTO (Data Transfer Object) class names MessageDto.ts and a service named chat.service.ts. You can create this service by running the following command.

ng generate service services/chat

Normally, we do HTTP requests and other external API calls in a separate service class as a best practice.

Write the following code inside the MessageDto.ts file. This DTO class is similar to the DTO class in the .NET core project.

Install SignalR Client Library

To connect via SignalR, we have to install the client SignalR library from the npm repository into your Angular project.

Run the following command to install the library.

npm install @microsoft/signalr --save

After installing the library we can use it to connect to the server. First, I will show the code in chat.service.ts file and then explain the implementation.

First, we have to import the functions in the library file and I have imported them all as ‘signalr’. Next, we have to build a connection with the hub. The URL path for the connection depends on the path given as the endpoint for the Hub at startup.cs file in the back-end (for me: “https://localhost:44379/chatsocket” ).

connection.on(<client_ method_ name>, <function_to_map>) , connection.start() and connection.onclose(<function_to_run>) have been used here.

connection.onclose() function invokes the function passed in when the connection with the server closes.

connection.start() function is used to start the connection with the server. I have wrapped this in another method and that method is called through the constructor.

connection.on() accepts two parameters. The first parameter is a name given to uniquely identify this on-connection. This parameter name should be as same as the first parameter used in the Hub’s method in the backend. ( See the highlighted name below).

Fig: 1.0

In Fig: 1.0, you can see another two parameters, user and message that are passed into the function defined as the second parameter of the function connection.on() in the chat.service.ts file.

retrieveMappedObject() is a public method used to share the data received from the backend, with other components in the project.

public broadcastMessage(msgDto: any) is used to call the backend API through an HTTP request that contains the message sent from this user.

I use app component to create the chatbox and make service calls.

What I do here is, when a new message has arrived, I push it into an array and display them in a chatbox.

I subscribe to retrieveMappedObject() method implemented in the service file through the ngOnInit() method.

Do not forget to inject the service through the constructor to use the service.

Finally, You will see a chat box like this. Open the Angular project in two browsers and try it.

Web view

Click me for the Demo or me for the source code.

Conclusion

Even though this is a simple chat app created using SignalR to demonstrate the use of SignalR with ASP.NET Core and Angular, SignalR is heavily used in many applications including Enterprise level apps to enable real-time communications and improve UX. This article is an introduction to SignalR too. But, you can improve this project with authentications and implement private chat options as well.

You can further read the following documentation notes to dive deeper into SignalR.

  1. How to use hubs in SignalR for ASP.NET Core.
  2. How to send messages from outside a hub.

Thank You.

--

--

Udith Gayan Indrakantha
LinkIT

Technology Enthusiast | Full Stack web Developer | Evernode Support Team | https://udith.netlify.com