SignalR在AspNetCoreWebAPI和Vue的使用
效果:(能实现消息推送,也能通过调用接口向所有客户端发送信息
一、Server端:
一、安装包
实现Hub:
public class ChatHub : Hub { [EnableCors("Policy")] public async Task BroadCast(string msg) { await Clients.All.SendAsync("broadcast", msg); } }
Startup中注入SiganlR、Cors服务
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("Policy", builder => { builder.SetIsOriginAllowed(_ => true).AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddSignalR(); }
app.UseCors(x => x.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<ChatHub>("/ChatHub"); });
Controller中调用:
[EnableCors("Policy")] [ApiController] [Route("api/[controller]/[action]")] public class SignalRController : ControllerBase { private readonly IHubContext<ChatHub> _hubContext; public SignalRController(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; } [HttpGet] public async Task<IActionResult> BroadCast(string msg) { await _hubContext.Clients.All.SendAsync("broadcast", msg); return Ok(); } }
这样后端就完成了:
二、Client端(Vue):
安装SiganlR:
npm install @microsoft/signalr
安装Jquery
npm i signalr jquery --save
页面代码:
<template> <div> <a>测试实时数据</a> <hr size="0.5" /> <input v-model="value" placeholder="请输入..." /> <Button type="info" @click="sendMsg()">发送</Button> <textarea name="txt" id="txtId" v-model="msg" cols="30" rows="10" ></textarea> </div> </template> <script> export default { name: "Home", data() { return { connection: "", value: "", msg: "", }; }, watch: { msg() { const textarea = document.getElementById("txtId"); textarea.scrollTop = textarea.scrollHeight; }, }, methods: { sendMsg() { this.connection.invoke("broadcast", this.value); //this.msg+="信息" }, init() { const signalR = require("@microsoft/signalr"); this.connection = new signalR.HubConnectionBuilder() .withUrl("http://localhost:5000/ChatHub/", {}) .build(); this.connection.on("broadcast", (data) => { //console.log("数据: " + data); this.msg += data += "\n"; }); this.connection.start(); }, }, created() { this.init(); }, }; </script>
常用的场景:
①广播推送;
②程序进度查看;
③页面新建Item时,id为数据库自增id,添加完成后需要拿该id进行下一步操作,后端添加成功自动推送该Item的Id到页面进行下一步操作,不需要局部刷新数据;