Table of contents
Client to Server Communication.
Hi all, we will be learning about SignalR with AspNetCore. In part one of this tutorial we will start with SignalR and Razor pages integration, then in part two we will integrate with Angular Framework.
Let's get started...
From theory, ASP.NET SignalR is a library for ASP.NET developers to add real-time web functionality to their applications. Real-time web functionality is the ability to have server-side code push content to the connected clients as it happens, in real-time.
Our main protagonists are:
AspNetCore.
Angular => Part 2
Here is the sneak preview for part 1.
Open the integrated terminal.
Create a folder SignalRChat
cd into SignalRChat
run dotnet new webapp.
cd SignalRChat/
dotnet new webapp
Below is the folder structure:
Add SignalR client library via the terminal.
In the integrated terminal, run the following command to install LibMan.
dotnet tool install -g Microsoft.Web.LibraryManager.Cli
Run the following command to get the SignalR client library by using LibMan.
libman install @microsoft/signalr@latest -p unpkg -d wwwroot/js/signalr --files dist/browser/signalr.js --files dist/browser/signalr.js
We now need to create a Hub class. This class will enable us to serve client server communication.
In the SignalRChat project folder, create a Hubs folder.
In the Hubs folder, create the
ChatHub
class with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("receiveMessage", user, message);
}
}
}
import Hub namespace using:
using Microsoft.AspNetCore.SignalR;
The ChatHub
class inherits from the SignalR Hub class. The Hub
class manages connections, groups, and messaging.
The SendMessage
method can be called by a connected client to send a message to all clients. JavaScript client code that calls the method is shown later in the tutorial. SignalR code is asynchronous to provide maximum scalability.
Add SignalR in our program.cs file
using SignalRChat.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub");
app.Run();
Add the content in Pages/Index.cshtml
with the following code:
@page
<div class="container">
<div class="row p-1">
<div class="col-1">User</div>
<div class="col-5"><input type="text" id="userInput" /></div>
</div>
<div class="row p-1">
<div class="col-1">Message</div>
<div class="col-5"><input type="text" class="w-100" id="messageInput" /></div>
</div>
<div class="row p-1">
<div class="col-6 text-end">
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<hr />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
The preceding markup:
Creates text boxes and a submit button.
Creates a list with
id="messagesList"
for displaying messages that are received from the SignalR hub.Includes script references to SignalR and the
chat.js
app code is created in the next step.
In the wwwroot/js folder, create a
chat.js
file with the following code:
Our chat.js file will look lik this.
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable the send button until connection is established.
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
The preceding JavaScript:
Creates and starts a connection.
Adds to the submit button a handler that sends messages to the hub.
Adds to the connection object a handler that receives messages from the hub and adds them to the list.
Finally run the app.
dotnet watch run
That's it,thank you for reading.See you soon in the next part where we will work with Angular and SignalR.