References Tutorial: Get started with ASP.NET Core SignalR
- Create .NET Core 2.2 Web Application
- Add Microsoft.AspNetCore.App nuget package
- Add signalr.js libraries (LibMan) and include the scripts to the index page
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
-
Create chat.js file into the js folder
-
Create a background service for sending regularly messages to the UI
public class BackgroundMessageSender : BackgroundService
{
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Sending msgs
Thread.Sleep(5000);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
- Add background service to startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//services.Configure...
services.AddHostedService<BackgroundMessageSender>();
}
}
- Create a Hub class with no content
public class NotificationHub : Hub
{
}
- Setup the Startup.cs for signal R
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSignalR();
services.AddHostedService<BackgroundMessageSender>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub"); // define an explicit route for the UI client
});
}
- Send messages from background service
public class BackgroundMessageSender : BackgroundService
{
private IHubContext<NotificationHub> _hubCtx;
public BackgroundMessageSender(IHubContext<NotificationHub> hubCtx)
{
_hubCtx = hubCtx;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Send directly a message to a different channel
await _hubCtx.Clients.All.SendAsync("ReceivedMessageFromServer", "ServerToClient: Message for all");
Thread.Sleep(5000);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Add this code to chat.js:
var notificationHub = new signalR.HubConnectionBuilder().withUrl("/notificationHub").build();
notificationHub.start();
notificationHub.on("ReceivedMessageFromServer", function (data) {
console.log(data);
});
- Hub class is created and startup.cs is setup
- Add a button in index.cshtml
<input type="button" id="triggerAction" value="Trigger actions into the server" />
- Add this code to chat.js:
var notificationHub = new signalR.HubConnectionBuilder().withUrl("/notificationHub").build();
notificationHub.start();
document.getElementById("triggerAction").addEventListener("click", function (event) {
notificationHub.invoke("TriggerAction", "exec").catch(function (err) {
return console.error(err.toString());
});
});
public class NotificationHub : Hub
{
public Task TriggerAction(string cmd)
{
Console.WriteLine("Command Received" + cmd);
return Task.CompletedTask;
}
}
Inside this method, you can do whatever you want such as:
- broadcast more messages for more other UI clients
await Clients.All.SendAsync("ReceiveMessage", msg)
- join a specific message group
await Groups.AddToGroupAsync(Context.ConnectionId, groupname)