一、前段代码:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
User..........<input type="text" id="userInput" />
<br />
Message...<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script type="text/javascript">
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/signalr").build();
//在建立连接之前禁用发送按钮
document.getElementById("sendButton").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("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();
});
</script>
</body>
</html>
原本var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//这种是在项目内的Hub文件夹内的charHub类指定的方式
更改var connection = new signalR.HubConnectionBuilder().withUrl("/signalr").build(); //类库的名称signalr
二、Startup.cs配置文件
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/SignalR"); //可以多个map
});
原本 routes.MapHub<ChatHub>("/chatHub"); //可以多个map ChatHub位于