Simple WebSocket with ASP.NET Core SignalR

Programming, error messages and sample code > ASP.NET

Create "ASP.NET Core Web App (C#)" in Visual Studio

Add the SignalR client library

  1. In Solution Explorer, right-click the project, and select Add > Client-Side Library.
  2. In the Add Client-Side Library dialog:
  3. Select unpkg for Provider
  4. Enter @microsoft/signalr@latest for Library.
  5. Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
  6. Set Target Location to wwwroot/js/signalr/.
  7. Select Install. LibMan creates a wwwroot/js/signalr folder and copies the selected files to it.
SignalR 1

Create a SignalR hub

In the project folder, create a Hubs folder.
In the Hubs folder, create the ChatHub class with the following code:
namespace WebApplication1.Hubs    // this name may be different from your project name
    public class ChatHub : Hub
        public async Task SendMessage(string user, string message)
            await Clients.All.SendAsync("ReceiveMessage", user, message);

Configure SignalR

The SignalR server must be configured to pass SignalR requests to SignalR. Add the following highlighted code to the Program.cs file.
using WebApplication1.Hubs;    // this name may be different from your project name

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();


Add SignalR client code

In the wwwroot/js folder, create a chat.js file with 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");
    // 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());
Replace the content in Pages/Index.cshtml with the following code:
@model IndexModel
    ViewData["Title"] = "Home 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 class="row p-1">
        <div class="col-1">Message</div>
        <div class="col-5"><input type="text" class="w-100" id="messageInput" /></div>
    <div class="row p-1">
        <div class="col-6 text-end">
            <input type="button" id="sendButton" value="Send Message" />
    <div class="row p-1">
        <div class="col-6">
            <hr />
    <div class="row p-1">
        <div class="col-6">
            <ul id="messagesList"></ul>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

Run the app locally

  1. Select Ctrl+F5 to run the app without debugging.
  2. Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.
  3. Choose either browser, enter a name and message, and select the Send Message button.
  4. The name and message are displayed on both pages instantly.
SignalR 2
The ChatHub connection serves at https://localhost:7266/chatHub. The WebSocket connection serves at wss://localhost:7266/chatHub (your port number may be different, and the id=xxx is automatically generated when establishing the connection).
SignalR 3

Publish to your hosting account

Test the app via your site temporary domain or your own domain

As you can see, the ChatHub connection serves at http://xxx, and the WebSocket connection serves at ws://xxx. If you access HTTPS://, they should be https://xxx and wss://xxx.
SignalR 4
Source link: