Sunday, July 19, 2020

How to Add SignalR in ASP.NET Core?

SignalR provides an API for creating server-to-client remote procedure calls (RPC). The clients can be JavaScript, .NET, or Java functions. Here are some of the main benefits to use SignalR as push architecture for real time applications.
  1. Handles connection management automatically.
  2. automatically chooses the best transport method that is within the capabilities of the server and client. (WebSocket, Server Sent Event, and Long Poll)
  3. Sends messages to all connected clients simultaneously. For example, a chat room.
  4. Sends messages to specific clients or groups of clients.
  5. Scales to handle increasing traffic.
It's very easy to set up an ASP.NET Core project with SignalR support in Visual Studio 2019 with Web Development tools. Hereunder are the key steps to enable SignalR in a web project with a browser client.

The SignalR server library is included in the ASP.NET Core 3.1 shared framework. The JavaScript client library isn't automatically included in the project. 

In Solution Explorer, right-click  wwwroot/js/ folder, and select Add Client-Side Library. If you don't see it in the context menu, please check if you have VS extension Microsoft Library Manager. 


Only select signalr.js and signalr.min.js.

              

After this you can create JS client now. Here is an example of JS client.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

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();
});

For more details to use SignalR in ASP.NET Core 3.1, please refer to the link below.



No comments:

Be A Developer That Uses AI

Developers will not be replaced by AI, they'll be replaced by developers that use AI. Generative AI tools are revolutionizing the way de...