1. Add SignalR client library
Right-click the project -> select "Add"> "Client Libraries"
Provider choice: unpkg , Bank Select: @ ASPNET / SignalR @ 1.1.4
Select "to select a specific file," expand "dist / browser" folder and select "signalr.js" and "signalr.min.js"
You can select specific location
2. Define Hub Hub
Creating MessageHub and inherit Hub. Hub class manages the connection, and group messages
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> /// client login user account and successfully saved client Id /// </ Summary> /// <param name = "loginNo"> </ param> public void SendLogin ( String loginNo) { // Analyzing the user has not landed (not insert the user name and login through Id, login user name, and by modifying Id) IF (! Connections.ContainsKey (loginNo)) { Connections.Add (loginNo, Context.ConnectionId); } the else { the Connections [loginNo] = Context.ConnectionId; } } } }
3. Configure SignalR
We need Startup.cs start classes ConfigureServices in registration SignalR Service
services.AddSignalR();
Set SignalR route
// set SignalR route to the custom class MessageHub app.UseSignalR (route => { route.MapHub <MessageHub> ( " / MessageHub " ); });
Note: UseSignalR must UseMvc call before!
4. Preparation SignalR client code
References signalr.js library file into the html
<!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 new signalR.HubConnectionBuilder () // Configure Route .withUrl ( " / MessageHub " ) // log information .configureLogging (signalR.LogLevel.Information) // Create .build (); // Accept message 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. Run the program
Open the html page, F12 to see the following information is printed explain the connection is successful in Console.
Enter text, click the send button. (I Alert here, if other requirements, may be received in the message processing logic inside callbacks)
6. dissemination of information from the controller
We can also send messages from the outside to the hub.
When using the controller, you need to inject a IHubContext instance.
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", "这是控制器发送的消息"); } } } }
调用接口测试