How to Send Real-Time Notifications with ASP.NET Core SignalR

Many of you might have heard about ASP.NET Core SignalR, an open-source library to send real-time web-based notifications. This article will help you build or integrate SignalR based notification in your ASP.NET Core web application.

Before we get into detail, let’s first look at what features it provides?

  • Handles connection management automatically.
  • Sends messages to all connected clients simultaneously. For example, a chat room.
  • Allow to send messages to specific clients or groups of clients.
  • Scales to handle increasing traffic.
  • SignalR for ASP.NET Core supports any server platform that ASP.NET Core supports.

How does it work?

SignalR provides API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers (and other client platforms) from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), and grouping connections.

Example

In this example we will send real-time notification to all online users when a new article is added by the admin. Users will instantly see the newly added article data.

  • Server will create a connection and return the new connection id to client hub proxy.
  • If the server wants to send the Notification to a user, it will find all the connectionId of a user and send it to the clients (by the connectionId).

We will do the example in two parts

  • Send real-time notification to all users
  • Send real-time notification to specific user

Let’s start:

1) Send real-time notification to all users

Step 1: Create ASP.NET Core web application.

using Microsoft.AspNetCore.SignalR;
namespace SignalRDemo.Hubs
{
public class NotificationHub : Hub
{
}
}
services.AddSignalR();
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>(“/NotificationHub”);
});

Step 7: Create Article.cs class file under Models folder and replace it with below code.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SignalRDemo.Hubs;
using Microsoft.AspNetCore.SignalR;
#articleList div {
text-align: left;
margin-bottom: 20px;
border-bottom: 1px solid #ccc;
}
#articleList div h3 {
margin-bottom:5px;
}
#articleList div p {
margin-bottom:5px;
}

2) Send real-time notification to specific user

Now, if you want to send notification to any specific user you have to make some tweaks in the code. And use Clients. Client method & pass connectionId of a specific user whom you want to send notification.

services.AddSingleton<IUserConnectionManager, UserConnectionManager>();
And go to Configure method and replace UseSignalR method with below line of code
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>(“/NotificationHub”);
routes.MapHub<NotificationUserHub>(“/NotificationUserHub”);
});
private readonly IHubContext<NotificationUserHub> _notificationUserHubContext;
private readonly IUserConnectionManager _userConnectionManager;
public AdminController(IHubContext<NotificationHub> notificationHubContext, IHubContext<NotificationUserHub> notificationUserHubContext, IUserConnectionManager userConnectionManager)
{
_notificationHubContext = notificationHubContext;
_notificationUserHubContext = notificationUserHubContext;
_userConnectionManager = userConnectionManager;
}
public string userId { get; set; }
[HttpPost]
public async Task<ActionResult> SendToSpecificUser(Article model)
{
var connections = _userConnectionManager.GetUserConnections(model.userId);
if (connections != null && connections.Count > 0)
{
foreach (var connectionId in connections)
{
await _notificationUserHubContext.Clients.Client(connectionId).SendAsync(“sendToUser”, model.articleHeading, model.articleContent);
}
}
return View();
}

Now you can input the userId and send notification to the user. As you can see in the below screenshots only the user with given id will receive the notification.

Conclusion

Done. We hope that article above help to explain more about SignalR Asp.net Core. If you are interested with Asp.net core, then you can always read our blog.

Related Posts

Leave a Reply

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