1.添加 SignalR 客戶端庫
右鍵點擊專案->然后選擇“添加” >“客戶端庫”
提供程式選擇:unpkg ,庫選擇:@aspnet/[email protected]
選擇“選擇特定檔案” ,展開“dist/browser” 檔案夾,然后選擇“signalr.js” 和“signalr.min.js”
選擇指定位置安裝即可

2.定義Hub集線器
創建MessageHub 并繼承Hub,Hub類管理連接、組和訊息
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; namespace NetCoreWebApi.SignalR { /// <summary> /// Message集線器 /// </summary> public class MessageHub : Hub { /// <summary> /// 存放已連接資訊 /// </summary> public static readonly Dictionary<string, string> Connections = new Dictionary<string, string>(); /// <summary> /// 發送訊息 /// </summary> /// <param name="loginNo"></param> /// <param name="message"></param> /// <returns></returns> public async Task SendMessage(string loginNo, string message) { Connections.TryGetValue(loginNo, out string clientId); //ReceiveMessage 客戶端接受方法 await Clients.Client(clientId).SendAsync("ReceiveMessage", message); } /// <summary> /// 客戶端登錄成功保存用戶賬號和客戶端Id /// </summary> /// <param name="loginNo"></param> public void SendLogin(string loginNo) { //判斷用戶有沒有登陸過(沒登陸過插入用戶名和Id,登陸過修改用戶名和Id) if (!Connections.ContainsKey(loginNo)) { Connections.Add(loginNo, Context.ConnectionId); } else { Connections[loginNo] = Context.ConnectionId; } } } }
3.配置SignalR
我們需要在Startup.cs啟動類的ConfigureServices中注冊SignalR服務
services.AddSignalR();
設定SignalR路由
//設定SignalR路由,指向自定義類MessageHub app.UseSignalR(route => { route.MapHub<MessageHub>("/MessageHub"); });
注意:UseSignalR 必須在 UseMvc 之前呼叫!
4.撰寫SignalR 客戶端代碼
參考signalr.js類別庫檔案到html中
在 on 后對 HubConnection 呼叫 start 方法,這樣做可確保在收到訊息之前注冊處理程式,
<!DOCTYPE HTML> <html> <head> </head> <body> <div style="text-align: center;margin-top: 5%"> <input type="text" id="message" placeholder="訊息" /> <button type="button" id="sendBtn">發送</button> </div> <script src="../Resources/lib/signalr/dist/browser/signalr.js"></script> </body> </html> <script> var connection = new signalR.HubConnectionBuilder() //配置路由 .withUrl("/MessageHub") //日志資訊 .configureLogging(signalR.LogLevel.Information) //創建 .build(); //接受訊息 connection.on("ReceiveMessage", (message) => { alert("收到訊息===>" + message); }); //發送訊息 document.getElementById("sendBtn").addEventListener("click", function () { var message = document.getElementById('message').value; connection.invoke("SendMessage", "[email protected]", message).catch(err => console.error(err.toString()) ); }); //開始連接 connection.start().then(e => { connection.invoke("SendLogin", "[email protected]").catch(err => console.error(err.toString()) ); }).catch(err => console.error(err.toString())); </script>
5.運行程式
打開html頁面,F12在 Console 看到列印以下資訊說明連接成功,

輸入文字,點擊發送按鈕,(我這里是alert,如有其它需求,可在接收訊息回呼里面處理邏輯)
6.從控制器發布訊息
將訊息從外部發送到 hub,當使用控制器時,需要注入一個 IHubContext 實體,
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using NetCoreWebApi.SignalR; namespace NetCoreWebApi.Controllers { /// <summary> /// SignalR推送 /// </summary> [Route("api/hub")] [ApiController] public class HubController : Controller { private readonly IHubContext<MessageHub> _hubContext; /// <summary> /// 建構式 /// </summary> /// <param name="hubClients"></param> public HubController(IHubContext<MessageHub> hubClients) { _hubContext = hubClients; } /// <summary> /// 測驗SignalR推送 /// </summary> /// <param name="loginNo"></param> [HttpGet] [Route("pushMsg")] public void PushMsg(string loginNo) { if (string.IsNullOrWhiteSpace(loginNo)) { //給所有人推送訊息 _hubContext.Clients.All.SendAsync("ReceiveMessage", "這是控制器發送的訊息"); } else { //給指定人推送 MessageHub.Connections.TryGetValue(loginNo, out string id); _hubContext.Clients.Client(id).SendAsync("ReceiveMessage", "這是控制器發送的訊息"); } } } }
呼叫介面測驗

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/87837.html
標籤:.NET Core
上一篇:Quartz.Net使用教程
