Introduction
SignalR is the open-source Microsoft API which is used to add real-time web functionality to the ASP.NET Core web application. SignalR provides a persistent connection between the client-server. It uses remote procedure calls shortly known as RPC to call the client from the server.
In this article, I’m going to show how to implement ASP.NET Core SignalR with a simple chat application with a user identity.
Create an ASP.NET Core Web application
Step 1: Create a new project in Visual Studio 2019
Step 2. Select ASP.NET Core Web application template. In my case, I named the project SignalRCoreApp
Step 3: Click on create, in the next wizard select web application template and click on the change link under the Authentication section.
Step 4: Select the individual user account from the popup, as shown in the below figure.
Create a SignalR Hub
Step 1: Right-click on the SignalRCoreApp project and create the Hub folder
Step 2: Add the Chat.cs file under the Hub folder
Chat.cs
- public class Chat: Microsoft.AspNetCore.SignalR.Hub
- {
- public async Task SendMessage(string message)
- {
- await Clients.All.SendAsync("ReceiveMessage",Context.User.Identity.Name?? "anonymous", message);
- }
- }
Context.User.Identity.Name gives the user name of the Identity based on the current user session.
Include the following namespaces:
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.SignalR;
Step 3: Open starup.cs file and let's configure the SignalR
Add the below code under the ConfigurationServices method:
Add the endpoints in the configure method:
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapRazorPages();
- endpoints.MapHub<Chat>("/chat");
- });
SignalR with JavaScript Client library
Step 1: Right-click on the project Add->Client-side Library
Step 2: The add client-side library wizard will appear, under provider section select unpkg
Step 3: Library- >enter @microsoft/signalr@latest
Step 4: Select specific files expand files->dist->browser->signalr.js, signalr.min.js
Step5: create a chat.js file under wwwroot->js folder
chat.js
- "use strict";
-
- var connection = new signalR.HubConnectionBuilder().withUrl("/Chat").build();
-
-
- document.getElementById("sendBtn").disabled = true;
-
- connection.on("ReceiveMessage", function (user, message) {
- var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
- var encodedMsg = user + " says " + msg;
- var li = document.createElement("li");
- li.textContent = encodedMsg;
- document.getElementById("ulmessages").appendChild(li);
- });
-
- connection.start().then(function () {
- document.getElementById("sendBtn").disabled = false;
- }).catch(function (err) {
- return console.error(err.toString());
- });
-
- document.getElementById("sendBtn").addEventListener("click", function (event) {
- var message = document.getElementById("txtmessage").value;
- connection.invoke("SendMessage", message).catch(function (err) {
- return console.error(err.toString());
- });
- event.preventDefault();
- });
Step 6: Open index.cshtml page and add the below code
- @page
- <div class="container">
-
- <div class="row">
- <div class="col-2">Message</div>
- <div class="col-4"><input type="text" id="txtmessage" /></div>
- </div>
- <div class="row"> </div>
- <div class="row">
- <div class="col-6">
- <input type="button" id="sendBtn" value="Send" />
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-12">
- <hr />
- </div>
- </div>
- <div class="row">
- <div class="col-6">
- <ul id="ulmessages"></ul>
- </div>
- </div>
- <script src="~/lib/@@microsoft/signalr/dist/browser/signalr.js"></script>
- <script src="~/js/chat.js"></script>
Run the application
Case 1: When user 1 –
[email protected] sends a message:
Summary
We have seen how to implement ASP.NET Core SignalR with an individual user account. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcome.
Happy Coding!