未定义ASP.NET Core 2.1 SignalR

Jia*_*nYA 6 javascript asp.net jquery signalr asp.net-core

这是我的聊天javascript

"use strict";

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

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

connection.start().catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("Send").addEventListener("click", function (event) {
    var message = document.getElementById("Message").value;
    connection.invoke("SendMessage", message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

这是我使用聊天输入运行页面时遇到的错误:

未捕获的ReferenceError:在chat.js:3中未定义signalR

第3行chat.js是:

var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();
Run Code Online (Sandbox Code Playgroud)

SignalR从Visual Studio添加客户端库下载了客户端库。我现在有一个名为文件jquery.signalR.js,它是ASP.NET SignalR JavaScript库2.4.0。

但是,此错误不会消失,由于某些原因,我无法继续。

Tan*_*jel 10

I see your application is ASP.NET Core but you are using jquery.signalR.js which is actually for ASP.NET MVC. SignalR client for ASP.NET Core is signalr.js which is independent of jQuery. You can download the signalr.js for ASP.NET Core from NPM:

You can also download using Visual Studio Client Side Library Manager (LibMan) as follows:

  • In Solution Explorer, right-click on the project, and select Add > Client-Side Library.

  • In the Add Client-Side Library dialog, for Provider select unpkg.

  • For Library, enter @aspnet/signalr@1, and select the latest version
    that isn't preview.

  • Must change Target Location to wwwroot/lib/signalr if it is anything else containing @ in the path. Otherwise it would not download.

在此处输入图片说明

For more details: Getting started with ASP.NET Core SignalR