asp.net core webapi signalR通信

1.前端使用npm 导入signalR的包和jquery包

npm install jquery -y

npm install @micosoft/signalr -y

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时通讯</title>
    <h1>signalr入门</h1>
</head>
<body>
    <input type="button" value="发送" id="btnSend">
</body>
</html>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/@microsoft/signalr/dist/browser/signalr.min.js"></script>
<script>
 //创建连接对象
 var connection=new signalR.HubConnectionBuilder()
 .withUrl("https://localhost:7177/myHub")
 .build();
//当连接成功时
connection.start().then(function(){
    console.log("客户端连接成功");
})
//接收服务端主动推送过来的消息
connection.on("ReceiveMsg",function(msg){
alert(msg)
})
connection.on("completeOrder",function(msg){
alert(msg)
})
$("#btnSend").click(function(){
//客户端主动调用服务定义的通讯方法
connection.invoke("SendMsg",1,"测试").catch(function(err){
console.log(err)
})
})
</script>

后端--program中注入signalR的服务和跨域服务

csharp 复制代码
 builder.Services.AddSignalR();
 //配置跨域
            builder.Services.AddCors(opt =>
            {
                opt.AddPolicy("ws.client", p =>
                {
                    p.AllowCredentials();
                    p.AllowAnyHeader();
                    p.AllowAnyMethod();
                    p.SetIsOriginAllowed(s => true);
                });
            });
 ......
 app.MapHub<MyHub>("/myHub");
 app.UseCors("ws.client");

新建一个hub类

csharp 复制代码
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;

namespace WebApplication1.Hubs
{
    public class MyHub : Hub
    {
        private readonly IMemoryCache _memoryCache;

        public MyHub(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        //当客户端成功连接时,会触发的方法
        public override Task OnConnectedAsync()
        {
            var cacheKey = "items_1";
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(30));

            _memoryCache.Set(cacheKey, Context.ConnectionId, cacheEntryOptions);
            return Task.CompletedTask;
        }

        //当客户端断开连接时,需要触发的方法
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            _memoryCache.Remove("items_1");
            return Task.CompletedTask;
        }

        public async void SendMsg(long userId, string msg)
        {
            string sendMsg = $"服务端收到了客户端的消息,参数user={userId},msg={msg}";
            //服务端主动推送消息给所有的客户端
            //await Clients.All.SendAsync("ReceiveMsg", sendMsg);
            //给除了自己以外的所有客户端发送消息
            await Clients.Others.SendAsync("ReceiveMsg", sendMsg);
        }
    }
}

控制器类

csharp 复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using WebApplication1.Hubs;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IMemoryCache _memoryCache;
        private readonly IHubContext<MyHub> _hubContext;

        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IMemoryCache memoryCache, IHubContext<MyHub> hubContext)
        {
            _logger = logger;
            _memoryCache = memoryCache;
            _hubContext = hubContext;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost]
        public void AddOrder()
        {
            var connectionId = _memoryCache.Get("items_1").ToString();
            //服务端向指定客户端发送信息。
            _hubContext.Clients.Client(connectionId).SendAsync("completeOrder", "订单完成");
        }
    }
}
相关推荐
shepherd枸杞泡茶1 天前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
csdn_aspnet1 天前
ASP.NET Core 简单文件上传
asp.net·.netcore
亦世凡华、3 天前
掌握.NET Core后端发布流程,如何部署后端应用?
经验分享·.netcore·docker部署·程序发布
contact973 天前
.NET Core中的五种过滤器详解
.netcore·过滤器
以为不会掉头发的詹同学3 天前
【 Avalonia UI 语言国际化 I18n】图文结合教学,保姆级教学,语言国际化就是这么简单(.Net C#)
开发语言·前端·c#·.netcore·用户界面
爱吃香蕉的阿豪5 天前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
shepherd枸杞泡茶5 天前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
.NET快速开发框架6 天前
使用nvm管理node.js版本,方便vue2,vue3开发
vue·.netcore·常用工具·开发技术·rdif
csdn_aspnet7 天前
ASP.NET Core 使用 FileStream 将 FileResult 文件发送到浏览器后删除该文件
asp.net·.netcore
csdn_aspnet7 天前
ASP.NET Core SixLabors.ImageSharp v1.0 的图像实用程序类 web示例
asp.net·.netcore