SignalR指定用户推送

2024-06-10 09:58
文章标签 指定 用户 推送 signalr

本文主要是介绍SignalR指定用户推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

添加SignalR推送官方文档:
https://docs.microsoft.com/zh-cn/aspnet/core/signalr/groups?view=aspnetcore-5.0

项目安装Microsoft.AspNetCore.SignalR包

配置集线器类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;namespace WebNetCore5_Img_Storage.Handler
{//继承IUserIdProvider用于告诉SignalR连接用谁来绑定用户idpublic class GetUserId : IUserIdProvider{string IUserIdProvider.GetUserId(HubConnectionContext connection){//获取当前登录用户idstring userid = connection.GetHttpContext().Session.GetString("user_id");return userid;}}public class ChatHub : Hub{public async Task SendMessage(string user, string message){await Clients.All.SendAsync("ReceiveMessage", user, message);}//特定用户推送消息public async Task SendPrivateMessage(string user, string message){await Clients.User(user).SendAsync("ReceiveMessage", message);}}
}

C#推送代码

 public class FileUploadController : BaseController{private readonly IHubContext<ChatHub> hubContext;public FileUploadController(IHubContext<ChatHub> _hubContext){        hubContext = _hubContext;}public async Task<ActionResult> UploadBigFile(IFormFile file)
{//当前登录用户idstring loginUserId=Current.Id;//后台上传进度decimal process = Math.Round((decimal)fileNo * 100 / total_minio_file_count, 2);	 //推送消息到前端hubContext.Clients.User(loginUserId).SendAsync("ReceiveMessage", loginUserId, process);								
}

配置启动类注册IUserIdProvider的实例

   // This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){//解决中文输出后被编码了services.Configure<Microsoft.Extensions.WebEncoders.WebEncoderOptions>(options =>{options.TextEncoderSettings = new System.Text.Encodings.Web.TextEncoderSettings(System.Text.Unicode.UnicodeRanges.All);});//services.AddControllersWithViews();//添加全局筛选器:services.AddControllersWithViews(options =>{options.Filters.Add(typeof(CustomExceptionFilter));})//自定义格式化json使用Newtonsoft.Json.AddNewtonsoftJson();//services.addNewservices.AddRazorPages();//session配置缓存组件依赖,分布式缓存//services.AddDistributedMemoryCache();//会话存活时间,单位(秒)int sessionTime = 0;int.TryParse(MyConfigReader.GetConfigValue("session_live_time"), out sessionTime);if (sessionTime == 0){sessionTime = 7200;}services.AddSession(options =>{//设置cookie名称//options.Cookie.Name = ".AspNetCore.Session";//会话滑动过期时间,距下次访问最小时间,超过则session失效options.IdleTimeout = TimeSpan.FromSeconds(sessionTime);options.Cookie.HttpOnly = true;options.Cookie.IsEssential = true;});//业务层注入  //services.AddScoped<IImgBLL, ImgBLLImpl>();string path = AppDomain.CurrentDomain.BaseDirectory;Assembly bll_impl = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.BLL.dll");Assembly bll_interface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IBLL.dll");var typesInterface = bll_interface.GetTypes();var typesImpl = bll_impl.GetTypes();foreach (var item in typesInterface){var name = item.Name.Substring(1);string implBLLImpName = name + "Impl";var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));if (impl != null){//services.AddTransient(item, impl);//services.AddSingleton(item, impl);services.AddScoped(item, impl);}}//数据层注册Assembly dalAssemblys = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.DAL.dll");Assembly dalInterface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IDAL.dll");var dalTypesImpl = dalAssemblys.GetTypes();var dalTypesInterface = dalInterface.GetTypes();foreach (var item in dalTypesInterface){var name = item.Name.Substring(1);string implDalName = name + "Impl";var impl = dalTypesImpl.FirstOrDefault(w => w.Name.Equals(implDalName));if (impl != null){//services.AddTransient(item, impl);services.AddScoped(item, impl);}}services.AddMvcCore();//用户IUserIdProvider实例注册services.AddScoped<Microsoft.AspNetCore.SignalR.IUserIdProvider, GetUserId>();//SignalR添加到服务services.AddSignalR();}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Error");}app.UseHttpsRedirection();app.UseStaticFiles(new StaticFileOptions(){//不限制content-type下载ServeUnknownFileTypes = true,配置的虚拟路径映射//RequestPath = "/local",物理地址//FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider("D:\\Work\\西南油气田图库系统\\WebNetCore5_Img_Storage\\WebNetCore5_Img_Storage\\bin\\Debug\\net5.0"),});app.UseRouting();//app.UseAuthentication();app.UseAuthorization();app.UseSession();//app.UseResponseCaching();//app.UseResponseCompression();//用MVC模式, 针对services的services.AddControllersWithViews();app.UseEndpoints(endpoints =>{//endpoints.MapDefaultControllerRoute();endpoints.MapRazorPages();endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");endpoints.MapHub<ChatHub>("/chathub");});

前端界面js代码

    <script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js"></script>//signalR推送消息,用于显示后台实时处理进度var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();connection.on("ReceiveMessage", function (user, message) {console.log("user=" + user + ",message=" + message);//后台上传视频到文件系统进度值$("#back_process_value").html(message+"%");});connection.start().then(function () {console.log("signalR推送连接成功");}).catch(function (err) {console.error("signalR推送连接异常");return console.error(err.toString());});//document.getElementById("sendButton").addEventListener("click", function (event) {//    var user = document.getElementById("userInput").value;//    var message = document.getElementById("messageInput").value;//    connection.invoke("SendMessage", user, message).catch(function (err) {//        return console.error(err.toString());//    });//    event.preventDefault();//});

这篇关于SignalR指定用户推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1047847

相关文章

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

springboot项目打jar制作成镜像并指定配置文件位置方式

《springboot项目打jar制作成镜像并指定配置文件位置方式》:本文主要介绍springboot项目打jar制作成镜像并指定配置文件位置方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录一、上传jar到服务器二、编写dockerfile三、新建对应配置文件所存放的数据卷目录四、将配置文

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

SpringSecurity显示用户账号已被锁定的原因及解决方案

《SpringSecurity显示用户账号已被锁定的原因及解决方案》SpringSecurity中用户账号被锁定问题源于UserDetails接口方法返回值错误,解决方案是修正isAccountNon... 目录SpringSecurity显示用户账号已被锁定的解决方案1.问题出现前的工作2.问题出现原因各

MySQL 用户创建与授权最佳实践

《MySQL用户创建与授权最佳实践》在MySQL中,用户管理和权限控制是数据库安全的重要组成部分,下面详细介绍如何在MySQL中创建用户并授予适当的权限,感兴趣的朋友跟随小编一起看看吧... 目录mysql 用户创建与授权详解一、MySQL用户管理基础1. 用户账户组成2. 查看现有用户二、创建用户1. 基

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

python如何生成指定文件大小

《python如何生成指定文件大小》:本文主要介绍python如何生成指定文件大小的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python生成指定文件大小方法一(速度最快)方法二(中等速度)方法三(生成可读文本文件–较慢)方法四(使用内存映射高效生成

Mysql中的用户管理实践

《Mysql中的用户管理实践》:本文主要介绍Mysql中的用户管理实践,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录13. 用户管理13.1 用户 13.1.1 用户信息 13.1.2 创建用户 13.1.3 删除用户 13.1.4 修改用户

python如何下载网络文件到本地指定文件夹

《python如何下载网络文件到本地指定文件夹》这篇文章主要为大家详细介绍了python如何实现下载网络文件到本地指定文件夹,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...  在python中下载文件到本地指定文件夹可以通过以下步骤实现,使用requests库处理HTTP请求,并结合o