SignalR is a popular open-source library for real-time web applications, which was first introduced by Microsoft in 2013. It allows developers to build scalable and interactive web applications by providing a powerful API for developing real-time communication applications in C#. In this article, we will explore the basics of SignalR and how it can be used to build real-time web applications in C#.
What is SignalR?
How does SignalR work?
SignalR uses websockets to create a bi-directional communication channel between the server and the client. This means that the server can push data to the client, and the client can push data back to the server in real-time. SignalR automatically chooses the best transport mechanism based on the client’s capabilities. It starts with WebSockets and falls back to other mechanisms like Server-Sent Events or Long Polling if WebSockets are not available.
SignalR in C#
To use SignalR in C#, you first need to install the SignalR package using NuGet. Once you have installed the package, you can start building real-time web applications using the SignalR API. Here’s a simple example of how to use SignalR in C#:
public class MyHub : Hub
public async Task SendMessage(string user, string message)
await Clients.All.SendAsync("ReceiveMessage", user, message);
In the example above, we have created a SignalR Hub called
MyHub. This Hub has a single method called
SendMessage that takes two parameters:
message. When this method is called, it sends a message to all connected clients using the
To use this Hub in your application, you first need to add the SignalR middleware to your application. Here’s an example of how to add SignalR to an ASP.NET Core application:
public class Startup
public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
In the example above, we have added the SignalR middleware to our application using the
AddSignalR method. We have also mapped our
MyHub class to the
/myHub endpoint using the