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

相关文章

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot实现不同接口指定上传文件大小的具体步骤

《SpringBoot实现不同接口指定上传文件大小的具体步骤》:本文主要介绍在SpringBoot中通过自定义注解、AOP拦截和配置文件实现不同接口上传文件大小限制的方法,强调需设置全局阈值远大于... 目录一  springboot实现不同接口指定文件大小1.1 思路说明1.2 工程启动说明二 具体实施2

java -jar example.jar 产生的日志输出到指定文件的方法

《java-jarexample.jar产生的日志输出到指定文件的方法》这篇文章给大家介绍java-jarexample.jar产生的日志输出到指定文件的方法,本文给大家介绍的非常详细,对大家的... 目录怎么让 Java -jar example.jar 产生的日志输出到指定文件一、方法1:使用重定向1、

基于Python实现数字限制在指定范围内的五种方式

《基于Python实现数字限制在指定范围内的五种方式》在编程中,数字范围限制是常见需求,无论是游戏开发中的角色属性值、金融计算中的利率调整,还是传感器数据处理中的异常值过滤,都需要将数字控制在合理范围... 目录引言一、基础条件判断法二、数学运算巧解法三、装饰器模式法四、自定义类封装法五、NumPy数组处理

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

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.问题出现原因各