Introduction

SignalR is an open-source library that facilitates to add real-time functionality on the web applications. Using this, the server application can push real-time data to the client.

Microsoft has provided different ways to connect with SignalR Server application from a client application using various client libraries. This article explains how to connect with signalR Server hub and receive the message data from the server to the client application using the SignalR .NET client in ASP.NET Core 6 application. As there are different ways to receive the data from SignalR server application to the client by utilizing different reference packages, in this article we will explore SignalR .NET client and use it in .NET 6 application to receive the data from the server hub. In this example, we will focus on a client application. This article explains and provides the code sample for the scenario where we have two different applications for SignalR server and client, and we need to use .NET client library for ASP.NET Core 6 application.

Prerequisites

  • Visual Studio 2022
  • Functioning SignalR Server Application

If you have already an existing client application in .NET 6.0, and you need to only implement the signalR .NET client to receive the real-time data from your server application, then you can directly jump into Step2.

Source

Step 1- Create an ASP.NET Core 6 project as usual

Open Visual Studio and click on Create a new project.

Select ASP.NET Core web app as illustrated below and click on Next.

Give the project name, location of the project, and click on Next.

Then select the Framework: .NET 6.0(Long-term support) as shown below and click on Create.

Then, your default signalr client app will be created. Which you can run and see the default design in the browser.

Now, let’s move to SignalR client part.

Step 2- Install SignalR .NET Client

Once, the project is created we can now, move to the signalr .net client part.

You can open the terminal in Visual Studio and can install the signalR .Net client using the below command.

Install-Package Microsoft.AspNetCore.SignalR.Client

Alternatively, you can search and install it from the NuGet Package manager as well.

Step 3 – Connecting to Hub (SignalR Server application)

Here, we will get familiar with the connection hub builder, which we will be required to connect with the server hub.

To make a connection, we need to create HubConnectionBuilder and start the Build, where we have to provide the server URL and message event. The below example withUrl contains the signalR server URL and signalR event hub name. You need to provide the correct value in the WithUrl in order to connect with the server.

var connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:53150/ChatHub")
                .Build();

Additionally, to reconnect automatically when the server connection gets lost, we can use WithAutomaticReconnect() method as well. Moreover, we can use StartAsync() method to start the connection asynchronously.

The complete code for the connection is

  connection = new HubConnectionBuilder()
            .WithUrl("http://localhost:39823/events-hub", options =>
            {
                options.Transports = HttpTransportType.WebSockets;
            })
            .WithAutomaticReconnect()
            .Build();
            await connection.StartAsync();

Let’s go to the project and create a connection with the Server and receive the message. For simplicity, I will use the Privacy Action Controller. In a real application, you can keep the connection and data receive code in your service class and call in wherever you need.

For simplicity, let’s go to Privacy Action of HomeController and create a connection with the SignalR server.

Here is the code of my HomeController Privacy.

public async Task<IActionResult> PrivacyAsync()
        {
          var  connection = new HubConnectionBuilder()
          .WithUrl("http://localhost:39823/events-hub", options =>
          {
              options.Transports = HttpTransportType.WebSockets;
          })
          .WithAutomaticReconnect()
          .Build();
            await connection.StartAsync();

            return View();
        }

using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.SignalR.Client; 

Note that: Above should be included in the controller And

  HubConnection connection; should be defined in the Home Controller.

Now, we need to change the default Privacy ActionResult to the Async as well.

Up to now, we have created the connection to the Server. Now we will move to receiving data in the client application.

To receive the data, write the following code just below the connection code in the same controller action.

public async Task<IActionResult> PrivacyAsync()
        {
          var  connection = new HubConnectionBuilder()
          .WithUrl("http://localhost:39823/events-hub", options =>
          {
              options.Transports = HttpTransportType.WebSockets;
          })
          .WithAutomaticReconnect()
          .Build();
            await connection.StartAsync();

            string newMessage1;
            connection.On<object>("receiveEvent", (message) =>
            {
                Console.WriteLine(message);
                var newMessage = JsonConvert.DeserializeObject<dynamic>(message.ToString());

                newMessage1 = $"{newMessage.chainTip}";              

            });

            return View();
        }

In my case, the server sends data to the client with the name receiveEvent. In the chat application, it can be ReceiveMessage. You can check your server code for your case.

Once, I have deserialized the data.

The complete code can be found here:

using DemoSignalRClientApp.Models;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using System.Diagnostics;

namespace DemoSignalRClientApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        HubConnection connection;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> PrivacyAsync()
        {
          var  connection = new HubConnectionBuilder()
          .WithUrl("http://localhost:39823/events-hub", options =>
          {
              options.Transports = HttpTransportType.WebSockets;
          })
          .WithAutomaticReconnect()
          .Build();
            await connection.StartAsync();

            string newMessage1;
            connection.On<object>("receiveEvent", (message) =>
            {
                Console.WriteLine(message);//write in the debug console
                var newMessage = JsonConvert.DeserializeObject<dynamic>(message.ToString());
                newMessage1 = $"{newMessage.chainTip}";              

            });

            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Hence, our client application is ready, we can run client and server applications at once and test whether the client app is able to receive data from server or not.

Below is the result of my Client application successfully receiving the data from the server.

Conclusion

Hence, in this article, we have learned to get the data in the client application from the server application using SignalR .Net client in ASP.NET Core web application.

As Microsoft has provided different ways to connect with SignalR Server application from a client application using various client libraries such as using .NET Client, JavaScript Client, Java Client, and so on. In the next part, we will learn how to use a JavaScript client library for the same purpose.

Reference

Microsost Docs

Leave a Reply

Your email address will not be published. Required fields are marked *