What are the prerequisites?
Environment: Visual Studio 2022 with ASP.NET and web development workloads
Create a web application project
In the Configure New Project dialog box, make an entry for the Project Name SignalRChat
.
Select " Next Page ".
In the Additional Information dialog box, select .NET 7.0 (Standard Term Support), and then select Create.
Add SignalR client library
The SignalR server library is included in the ASP.NET Core shared framework. The JavaScript client library is not automatically included in the project, for this tutorial, use the library manager (LibMan) to obtain the client library from unpkg. unpkg
is a fast global content delivery network for all content on npm .
In Solution Explorer > Right-click the project and select Add Client Library.
In the Add Client Library dialog box:
- Select "unpkg" for "Provider"
- For Library, enter
@microsoft/signalr@latest
. - Select Select specific files, expand the dist/browser folder, and select
signalr.js
andsignalr.min.js
. - Set "Destination Location" to
wwwroot/js/signalr/
. - Select Install.
LibMan creates wwwroot/js/signalr
a folder and copies selected files to the folder.
Create SignaIR Center
Hub is a class that serves as a high-level conduit for handling client-server communication.
In the SignalRChat project folder, create Hubs
the folder.
In Hubs
the folder, create ChatHub
the class with the following code:
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);
}
}
}
ChatHub
Class inherited from SignalR Hub . Hub
Classes manage connections, groups, and messages.
Can be called from connected clients SendMessage
to send messages to all clients. The JavaScript client code that calls this method is shown later in this tutorial. SignalR code is asynchronous, providing maximum scalability.
Configure SignalR
The SignalR server must be configured to pass SignalR requests to SignalR. Add the following highlighted code to Program.cs
the file.
using SignalRChat.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub");
app.Run();
The code highlighted above adds SignalR to the ASP.NET Core dependency injection and routing system.
Add SignalR client code
Replace Pages/Index.cshtml
the content in 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>
Previous tags:
- Create a text box and submit button.
- Use to
id="messagesList"
create a list that displays messages received from the SignalR hub. - Include a script reference to SignalR and create the application code in the next step
chat.js
.
In wwwroot/js
the folder, create chat.js
the file using the following code:
"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();
});
Previous JavaScript:
- Create and start the connection.
- Add a handler to the Submit button that sends a message to the hub.
- Adds a handler to the connection object that receives messages from the hub and adds them to the list.
achieve effect
hint:
If the app doesn't work, open your browser developer tools (F12) and go to the console. Find possible errors related to HTML and JavaScript code. For example, if signalr.js
placed in a different folder than indicated, a reference to the file will not work, resulting in a 404 error in the console.
If an error occurs in Chrome ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
, run the following command to update the development certificate:
.NET CLI
dotnet dev-certs https --clean
dotnet dev-certs https --trust