Implementation of SignalR in Asp.Net (Backend part)
In my previous article I already talked about receiving Signal R messages from Server using Angular 5 application. Here is the Link
In this small article I’ll walk you through how implement Signal R & set up notification messages on the Server side (Asp.Net Web API 2.0).
ASP.Net application
To get started, we need to first create an empty ASP.Net application is created, go to solution explorer –> Right click on project and choose “Manage Nuget Package”. When the Package Manager window is opened search for the SignalR package.
Install the Microsoft ASP.NET SignalR package from PM
Add a ServerHub class inherited from Hub (SignalR class)
public class ServerHub : Hub
{}
Add methods to the above class to notify or push the messages to the clients (by registering multiple clients)
public void RegisterForNotification(string clientId)
{
Groups.Add(Context.ConnectionId, clientId);
}public static void NotifyClient(string clientId, object data)
{
var hubContext = GlobalHost.ConnectionManager.
GetHubContext<ClientHub>();
hubContext.Clients.Group(clientId).
clientUpdated(data);
}public static void BroadCastMessage(string message)
{
var hubContext = GlobalHost.ConnectionManager.
GetHubContext<ClientHub>(); hubContext.Clients.All.
getMessageFromServer(message);
}
Now create a new class ClientNotification as an utility class which will access all the methods from ServerHub class
public class ClientNotification
{
public void BroadCastMessage(string message)
{
ServerHub.BroadCastMessage(message);
} public void NotifyClient(string clientId, Notification notify)
{
ServerHub.NotifyClient(clientId, notify);
}
}
Now last thing is to configure the SignalR in Start up class to make it ready for use
app.Map("/signalr", map => {
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration();
map.RunSignalR(hubConfiguration);
});
That’s pretty much about how you implement SignalR in Asp.Net application
That’s about it. Happy Coding