Real-time applications are becoming necessary to provide instant responses and improve user satisfaction. As .NET is considered a reliable technology for building business solutions, it also offers a library called SignalR. It helps to develop real-time web apps and also aids in managing client connections.
In addition, you don’t need additional software or hardware to develop an ASP.NET Core SignalR app. You can curate it using the latest version of Visual Studio and the .NET framework. In this blog, you will undergo a SignalR tutorial, helping you understand the working and process of curating a real-time ASP.NET core web app.
How to Use SignalR in ASP.Net Core – All-in-One Tutorial
Real-time web applications are trending, and most organizations prefer it for better efficiency and productivity. And as you know that .NET is the first choice of firms when it comes to curating a reliable business solution.
To embrace businesses with .NET and real-time functionality, Microsoft has released ASP.NET Core SignalR. Using it, you can create a real-time web application to respond faster to user inputs.
Let’s get started with a brief on SignalR .NET Core and move toward the practical implementation/SignalR tutorial.
What is SignalR?
SignalR is a software development library that gets used to build real-time ASP.NET applications. The library is available under an open-source license; anyone can use it for their .NET Core development services. In addition, the primary purpose of ASP.NET Core SignalR is to instantly push content from the server to the client side.
Moreover, the main use cases of SignalR .NET Core are:
- Social networking websites and applications
- GPS-enabled applications
- Real-time data monitoring applications
- Team meeting and collaboration applications
- Chat rooms, flight booking sites, games, and similar software
Furthermore, the top features of SignalR .NET Core include:
- Automated connection management
- Broadcasting messages to all connected clients
- Sending a message to a particular authenticated client
- Seamless handling of high-traffic load
Also, SignalR uses three primary methods to conduct and handle communications: WebSocket, Server-Sent events, and Long Polling. It also utilizes a hub, which is a crucial component and must configure a high-level pipeline. The SignalR uses the hub to enable server and client-to-call methods.
How To Use SignalR in ASP.NET Core?
To understand the use and how SignalR sends a message from the server, we are going to create an ASP.NET Core project. Before you start with the implementation, install the 2022 or above version of the community edition Visual Studio. In addition, we are going to use .NET 6 SDK for this tutorial.
Furthermore, our complete tutorial is divided into six primary steps, under which you will get to know about all associated sub-tasks. The procedure starts by creating a project and ends by utilizing SignalR in the ASP.NET Core application.
Once you understand the procedure, most of your queries about ASP.NET Core SignalR will get cleared. So, let’s start with the SignalR .NET Core tutorial.
Step 1: Create a new ASP.NET Core Project in Visual Studio
Once you install Visual Studio on your system, open it and create a new project.
Firstly, click on the Create a new project option and then on the ASP.NET Core web app (Model-View-Controller). Further, start configuring the new project by setting up the name, location, and solution name. Lastly, fill out the additional details, including framework and authentication type, and then click on the Create button.
As a result, your ASP.NET Core project will be created, which will be used to implement SignalR and understand its functioning.
Step 2: Complete Installation of the necessary packages
After creating a new project, it’s time to install the required packages so that SignalR can send messages from the server. In this tutorial, we use .NET 6, which eliminates the need to install server-side packages. So, we are going to install packages for our client-side configuration.
To install the packages, follow the below steps:
- Go to the solution explorer section, available on the ride side of the screen.
- Discover the project and right-click on it to open the menu click on Add, and then on Client-side library.
- Once the package installation interface opens, input “unpkg” as the provider and “@microsoft/signalr@latest” as the library.
- Select the files you need, select storage location, and hit the install button. For this tutorial, choose the following two files:
- File/dist/browser/signalr.js
- File/dist/browser/signalr.min.js
After the successful installation of required client-side packages, you can view them from the solution explorer. All the packages will be available under wwwroot/lib/microsoft/signalr/dist/browser.
Step 3: Perform Server Configuration
Now, we are going to configure the server where the client will send the requests. The server configuration step will get completed in two phases. In the first phase, you will create a SignalR hub; in the second phase, you will add code for the SignalR ASP.NET Core application. In addition, the code provided is written in C# language.
Let’s complete each phase one by one.
Phase 1: Generation of SignalR Hub
The SignalR hub will be used as a point of communication. All clients will send a request to the hub, and it will provide them with the messages. You should derive a class from the Hub base class as provided below.
The class MessageHub is the derived class, and under it, the SendMessage method is created with the user and message string. Both strings will get used to define the receiver and the message itself. However, if the receiver doesn’t get defined, the SignalR application will broadcast the message to all connected client devices.
Further, the SendAsync method is used with the if-else decision-making statement. The primary aim of defining this method is to decide whether the SignalR server should send a message to a single user or all clients.
The phase completes here.
Phase 2: ASP.NET Core SignalR Configuration
Now, you should navigate to the solutions explorer and open the Program.cs file. After opening it, add the following code and save it.
By wiring this code, you are configuring the SignalR service, which will get activated automatically once the application starts. Moreover, the endpoint also has been configured in the code, which will help the client devices to connect with the SignalR hub/server.
Step 4: Write the code for the Client device
After the SignalR server/hub configuration, you need to set up the client side. We will add the JavaScript code, enabling client devices to connect with the SignalR hub and receive messages.
To add the JavaScript code, create a file under the wwwroot/js/named ConnectSignalR.js. You can also set any other name, but we are using ConnectSignalR.js for this tutorial. Further, after creating the files, add the following code and save it.
After saving the JavaScript file, you should load it in the C# HTML file as below with the name – _Layout.cshtml. This C# HTML file will get utilized by the Razor markup engine on the server side for the page rendering procedure. However, only authenticated users will receive permission to access the files.
The code in the C# HTML file will let authenticated users connect with the SignalR hub and receive messages. Although, some additional configuration is required to let clients sign in to the ASP.NET Core application.
Once again, open the _Layout.cshtml file and put the following inside it to utilize SignInManager.
Finally, the server and client side are configured and ready. Now, the end-users can sign in to the app and receive messages through the server. But our procedure continues, as you need to create an interface for the client side.
The interface will help the users to send messages to all other clients connected to the SignalR hub.
Step 5: Create the user interface
As we have selected the model-view-controller project, we are going to add code for all three components to build the client interface.
Under the controller, open the HomeController.cs file to add the following code inside it.
Save the above code and open another file by following the path – Views/Home/SendMessage.cshtml.
Now, add the below code to SendMessage.cshtml file.
The above code will allow only authenticated users to send messages to other clients connected to the network. The interface will get displayed to all logged-in clients, but permission to send messages will be provided as per roles and responsibilities.
Further, navigate to the SendMessage.js file through the wwwroot/js/ path and add the following code. It would help the clients to execute a remote procedure for calling the method (SendMessage) defined in the hub.
Now, we are almost ready with our SignalR ASP.NET Core application. One last code is remaining, which you need to add in the _Layout.cshtml file. The purpose of the code is to add a menu on the interface from where the end-users can call the SendMessage method. And as per our previous code, only authorized and authenticated users will get access to it.
Finally, you have completed the coding part; now, only application testing remains.
Step 6: Run the Code and Confirm the Output
We are in the testing phase now to confirm the functionality of our real-time SignalR ASP.NET Core application. To test the app, you are going to create three users, utilizing different browsers to send and receive the message.
We will verify functionality through two test cases – sending a message to a specific user and broadcasting the message to all clients. But, before you run the application, open the package manager and console and run the following commands:
Now, create three users and log in from different browsers, as displayed in the snippet below.
After creating and logging all three users, go to any of the browsers and click the Send Message option. As per our first test case, define the user and the message and click the send message button.
As a result, you will see that the defined user only received the message.
Furthermore, as per our second test case, don’t define the user, input only the message and click on Send Message button. You will see that all the clients connected to the SignalR hub received the message. Thus, the SendMessage method we defined in the hub code gets called, and SignalR executes the real-time communication.
Therefore, now you know that SignalR gets used for real-time applications, and its working is based on server and client architecture.
Concluding Up
From the SignalR tutorial provided above, you can understand the functionality of an ASP.NET Core SignalR application. It will provide a clear insight into how a real-time web application works and how the SignalR hub maintains communication between the server and end-user.
Further, with the help of this open-source library, you can create your real-time applications. And if you need experts to work on your project, you can contact Positiwise Software Pvt Ltd.
Interesting Related Article: “Proxy servers explained: How Do They work?“