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到页面进行下一步操作,不需要局部刷新数据;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构