SignalR .Net Core. Learn the basics

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

SignalR .Net Core is a popular open-source framework that helps developers to building real-time web applications. It allows the server to send asynchronous messages to connected clients. The first version was released by Microsoft in 2013 with the ASP.NET framework. The latest framework is based on the .Net Core eco system. In the article I will cover all the basics that will allow you to integrate this framework in your application.

What is SignalR?

SignalR is a framework that allows server to send instant content and notifications to the connected client applications. It is useful when the client requires heavy updates from server frequently like voting applications, gaming, social applications etc. It provides an API to create remote procedure calls in client server applications. The RPC calls call can be consumed by a variety of client types and languages. .

SignalR has gained the popularity after the recent advancement in .NET core framework. This article will help you in creating a hub and implementing a client to establish the communication between the client and a server.

Features

  • Handles the connections between client and server automatically
  • Can send the messages to all the connected clients simultaneously
  • Allows the user to send and receive messages from the restricted group of clients only
  • Helps in managing the increased traffic
  • Supports more than one technique to support the communication between a client and server
  • Choses the best technique atomically depending on the capabilities of server and a client

What are Transports?

Transports are used to handle the real time communications between server and a client. It handles the best transport method based on the capabilities of an application shared between two of them. Let us walk through the each type of Transports in brief detail:

Long Polling

In this type of transport, a new pipeline is opened up, typically called as AJAX call for the server to communicate for the possible future requests by the client. Whenever the sever wants to send a message to the client, it automatically uses the recent opened up Pipe to communicate with the client, and when the communication is completed, the connection is closed. For the subsequent communications, a client will have to reestablish the connection. In an ideal situation, when the server is continuously sending data, it will keep on reestablishing the connection but this process can bring an overhead on the sever.

Web Sockets

Web Sockets typically works on one to one connection between the client and the server. In this type of transport, the communication is made on the existing pipe, which is opened for the first time. In order to deploy web socket application on IIS, you need to have version 8 or greater as it cannot work on version 7 or older.

Server Sent Events (SSE)

In Server Sent Events, a server creates an object called as Event Source, which is a pipe for the client and every time a server needs to send a data, it uses the same pipe. It is supported on all the modern browsers except Internet Explorer.

Forever Frame (FF)

Forever Frame is only available on Internet Explorer only. In this type, an Iframe is created on the same page when the connection is established between the server and the client. The server will keep on using the same connection as the connection is always opened and never closed by the client.

What are Hubs?

Hubs provides a medium to communicate between a client and server in an application. It allows each other to send and receive data from each other. You can define methods on server side and client side called by each other and SignalR handles the execution of methods on the server sent by the client and vice versa. It allows you to pass messages by using the text based protocol JSON or the binary one i.e. MessagePack. MessagePack is generally smaller as compared to JSON.

How to create a SignalR Hub?

You can create a hub that can handle a communication between server and client. You must download SignalR module using a node package manager and copy signalr.js in your project.

Let us take a .NET Core project and add a MyChatHub class, inherited from the SignalR Hub class. In this class, you need to create a method “SendMessage” and call the “ReceiveMessage” method of the connected client.

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

namespace MyChatApp
{
    public class MyChatHub : Hub
    {
        public async Task SendMessage(string userName, string chatMessage) 
        {
            await Clients.All.SendAsync("ReceiveMessage", userName, chatMessage);  
        }
    }
} 

You can configure the hub class in the Startup class of the .Net project:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyChatApp.Hubs;

namespace MyChatApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // Use this method to add services to the container.
       public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddSignalR();
        }

        //Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/ErrorPage");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
               endpoints.MapHub("/chatHub");
            });
        }
    }
}

Your main class will look like this:

namespace MyChatApp
{
    public class Program
    {
       // This is the entry point when the application runs, it is called first 
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });
    }
}

In .NET Core SignalR application, you can use .NET client library to communicate with the server. Before implementing a client, you must have setup the hub class for the client and it must has a method which can be used from the JavaScript and the mapping of hub is also completed. In the Startup class of the .NET core project.

Let us take the above example of MyChatHub class, in which you have a method SendMessage which will call the RecieveMessage method of the connected client. Therefore, you need to create a js file in your wwwroot/js folder and create that method in it.

const connection = new signalR.HubConnectionBuilder()  
    .withUrl("/myChatHub")  
    .build();  
  
//This method will receive the message and add to our list  
connection.on("ReceiveMessage", (userName, chatMessage) => {  
    const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");  
    const encodedMsg = user + " :: " + msg;  
    const li = document.createElement("li");  
    li.textContent = encodedMsg;  
    document.getElementById("messagesList").appendChild(li);  
});  
  
connection.start().catch(err => console.error(err.toString()));  
  
//Send the message  
document.getElementById("sendMessage").addEventListener("click", event => {  
    const user = document.getElementById("userName").value;  
    const message = document.getElementById("userMessage").value;  
    connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));  
    event.preventDefault();  
});   

Once the js code is written, you need to add the following code to the view:

<!DOCTYPE html>
<html>
      <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>My Real Time Chat App </title> 
      </head>
<body>
      <div class="container"> 
         <div class="row"> 
              <div class="col-md-12"> 
                   <div class="col-md-6"> 
                        <div class="col-md-3">User</div> 
                        <div class="col-md-9"><input type="text" id="userName" /></div> 
                    </div> 
              </div> 
         <div class="col-md-12"> 
              <div class="col-md-6"> 
                    <div class="col-md-3">Message</div> 
                         <div class="col-md-9"> 
                               <input type="text" id="userMessage" /> 
                               <input type="button" id="sendMessage" value="Send Message" /> 
                         </div> 
                    </div> 
              </div> 
        </div> 
        <div class="row"> 
             <div class="col-12"> 
                  <hr /> 
             </div> 
         </div> 
         <div class="row"> 
              <div class="col-6"> </div> 
              <div class="col-6"> 
                   <ul id="messagesList"></ul> 
              </div> 
         </div> 
</div> 
<script src="~/lib/signalr/signalr.js"></script> 
<script src="~/js/mychat.js"></script> 
</body>
</html>

How to add Authentication and Authorization?

Authentication

If you are creating a web application that requires authenticated users to access it, then you need to add .NET Core authentication module to the application. All the connections will be available to the authentic users.

Here is the code of Startup class that configures the .NET core authentication in SignalR application:

public void Configure(IApplicationBuilder app)
{
    // Your custom code here 
 
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub("/chat");
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}

Authorization

In .NET Core SignalR application, all the methods are exposed to unauthenticated users. In order to apply the authentication filters, you can use [Authorize] attribute to the hub in an application.

You can simply use the following code to achieve the authorization:

[Authorize]
public class ChatHub: Hub
{
      // Your code here
}

You can create a custom authorization policy and pass the policyname as an argument to the constructor of the attribute to apply it on the hub. The filter will ensure that the users that are matching with the policy will have access to it.

[Authorize("AppAuthorizationPolicy")]
public class ChatHub : Hub
{
}

If you wish to apply policy to the restricted method, you can apply it on the individual method and the other methods will not be affected by the policy. Let us suppose you want to apply filter of admin users on a single method i.e. only admin users can have an access to the confidential information.

[Authorize]
public class ChatHub : Hub
{
    public async Task Send(string message)
    {
        // Your code here to send a message to all the users 
    }

    [Authorize("Admins")]
    public void ShowAllUsers(string departmentID)
    {
        // You code here to show the list of users from the chat room which is only visible to admin users
    }
}

Differences Between ASP.NET SignalR and ASP.NET Core

Although .NET Core SignalR has the same core concepts and functionalities that ASP.NET Signal had, there are some noteworthy changes between both of them.

 

JavaScript Client Library

In .NET Core, one of the major change is the removal of jQuery library. You can use JavaScript or TypeScript libraries without having a reference of jQuery. This feature allows the application to be used in Node.js and it can support the multiple popular frameworks like Angular, Vue and React with adding any complexity to the code.

Dependency Injection

In ASP.NET, you do not have built-in capability of dependency injection to resolve the dependencies. GlobalHost is class is used to resolve all the dependencies provided by SignalR. .NET Core framework has the power of built-in Dependency Injection (DI) and Inversion of Control (IoC) functionalities that resolves the dependencies automatically without any explicit need of writing DI code.

Custom Protocols

.NET Core and ASP.NET both support JSON, whereas .NET Core Signal supports the newer version of JSON and it supports the binary protocol that has smaller payloads as compared to JSON protocol. Moreover, it also allows you to create some custom protocols in it.

Reconnections

In ASP.NET, the application reconnects automatically if the connection is broken or dropped out, whereas in .NET Core, it does not support automatic reconnection.

Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.