ASP.NET Core SignalR实时推送配置,业务层实时推送SignalR消息

web框架版本:.NET 6
不需要安装nuget有关signalr的包

微软参考文档:
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/signalr?view=aspnetcore-6.0&tabs=visual-studio

Startup.cs配置

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;


namespace WebMvcNetCore.TuShi.FenGong
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
  
                services.AddSignalR();
                services.AddMvcCore();
        
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseRouting();   
            app.UseAuthorization();
            app.UseStaticFiles();
 

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Main}/{id?}");
					
                endpoints.MapHub<Models.ChatHub>("/chatHub");
            });



        }
    }
}

web项目中配置集线器类

namespace WebMvcNetCore.TuShi.FenGong.Models
{
    /// 
    /// 消息推送集线器
    /// 
    public class ChatHub : Microsoft.AspNetCore.SignalR.Hub
    {
        //public void Revice() {
        //    Clients.All.SendAsync("ReceiveMessage", user, message);
        //}
    }
}


添加SignalR的前端js文件
ASP.NET Core SignalR实时推送配置,业务层实时推送SignalR消息_第1张图片

*.cshtml页面代码


 <div class="table-fun" id="workHandMsg" style="color:#FF33FF;margin-right:300px;font-weight:bold;">                
            div>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js">script>
<script type="text/javascript">
    //后台推送到页面消息
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    connection.start().then(function () {
         console.log('signalR连接成功');
    }).catch(function (err) {
        return console.error(err.toString());
    });
    connection.on("ReceiveMessage", function (message) {
        //console.log(message);
         console.log('后台消息:'+message);
         $("#workHandMsg").html(message);
    });
script>




在业务层需要推送的地方代码参考,这里用了委托
WorkerController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MvcSimplePager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IBusiness;
using WebMvcNetCore.TuShi.FenGong.Model;
using WebMvcNetCore.TuShi.FenGong.Models;

namespace WebMvcNetCore.TuShi.FenGong.Controllers
{
    /// 
    /// 工人管理
    /// 
    public class WorkerController : BaseController
    {
		readonly IWorkBusiness workBusiness;
        readonly IDepartmentBusiness departmentBusiness;

        public WorkerController(IWorkBusiness _workBusiness
           , IDepartmentBusiness _departmentBusiness)
        {
            workBusiness = _workBusiness;
            departmentBusiness = _departmentBusiness;
        }


        //批量导入工人   创建时间:2021-12-9 17:43:03
        public async Task<IActionResult> ImportWorker(IFormFile file)
        {
            //推送工人处理进度消息到前端页面
            var _contextHub = (Microsoft.AspNetCore.SignalR.IHubContext<ChatHub>)HttpContext.RequestServices.GetService(typeof(Microsoft.AspNetCore.SignalR.IHubContext<ChatHub>));
            Action<string> action = async (msg) =>
            {
                object[] arr = { msg };
                await _contextHub.Clients.All.SendCoreAsync("ReceiveMessage", arr);
            };

            var result = await workBusiness.ImportWorker(file.OpenReadStream(), GetWebLoginUser.Sys_manager_id, action);
            return Json(result);
        }
	}
}

IWorkBusiness.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.IBusiness
{
    /// 
    /// 工人业务处理
    /// 
    public interface IWorkBusiness
    {
        /// 
        /// 批量导入工人
        /// 
        /// excel文件流
        /// 登录人id
        /// 推送消息回调
        /// 
        /// 
        /// 创建时间:2021-12-9 17:42:08
        /// 
        Task<Result> ImportWorker(System.IO.Stream stream, string loginUserId,Action<string> func);

   }
}

IWorkBusiness.cs实现类:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IBusiness;
using WebMvcNetCore.TuShi.FenGong.IDAL;
using WebMvcNetCore.TuShi.FenGong.Model;
using WebMvcNetCore.TuShi.FenGong.Model.Tool;

namespace WebMvcNetCore.TuShi.FenGong.BusinessImpl
{
    /// 
    /// 获取工人,接口实现
    /// 
    public class WorkBusinessImpl : IWorkBusiness
    {
        readonly IWorkerDAL workerDAL;
        readonly IDepartmentBusiness departmentBusiness;
        readonly IProject_selected_workerDAL project_Selected_WorkerDAL;
        readonly IOperate_logDAL operate_LogDAL;
        readonly IDepartmentDAL departmentDAL;

        public WorkBusinessImpl(IWorkerDAL _workerDAL
            , IProject_selected_workerDAL _project_Selected_WorkerDAL
            , IOperate_logDAL _operate_LogDAL
            , IDepartmentDAL _departmentDAL
            , IDepartmentBusiness _departmentBusiness)
        {
            departmentDAL = _departmentDAL;
            workerDAL = _workerDAL;
            departmentBusiness = _departmentBusiness;
            project_Selected_WorkerDAL = _project_Selected_WorkerDAL;
            operate_LogDAL = _operate_LogDAL;
        }

        /// 
        /// 批量导入工人
        /// 
        /// excel文件流
        /// 登录人id
        /// 推送消息回调
        /// 
        public async Task<Result> ImportWorker(System.IO.Stream stream, string loginUserId, Action<string> func)
        {
            if (string.IsNullOrWhiteSpace(loginUserId))
            {
                return new Result("loginUserId不可为空");
            }
            List<Worker> list = new List<Worker>();
            try
            {
                Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(stream);
                Aspose.Cells.Worksheet sheet = wb.Worksheets[0];
                Aspose.Cells.Cells cells = sheet.Cells;
                if (cells.Rows.Count == 1)
                {
                    return new Result("导入数据至少一行");
                }
                func("获取到记录数"+ (cells.Rows.Count-1));

                for (int i = 1; i < cells.Rows.Count; i++)
                {
                    func($"检查第{i+1}行记录数据...");

                    var row_cells = cells.Rows[i];
                    Worker worker = new Worker();
                    worker.Person_id = Guid.NewGuid().ToString("n");
                    worker.Createtime = DateTime.Now;

                    //姓名
                    var xing_ming_cell = row_cells.GetCellOrNull(0);
                    if (xing_ming_cell == null)
                    {
                        return new Result("姓名不可为空,行号" + i);
                    }
                    worker.Real_name = xing_ming_cell.StringValue;
                    if (string.IsNullOrWhiteSpace(worker.Real_name))
                    {
                        return new Result("姓名不可为空");
                    }

                    //性别
                    worker.Gender = false;
                    var xb_cell = row_cells.GetCellOrNull(1);
                    if (xb_cell != null)
                    {
                        if (xb_cell.StringValue == "男")
                        {
                            worker.Gender = true;
                        }
                        else
                        {
                            worker.Gender = false;
                        }
                    }

                    //身份证号
                    var idcard_cell = row_cells.GetCellOrNull(2);
                    if (idcard_cell == null)
                    {
                        return new Result("身份证号不可为空,行号" + i);
                    }
                    worker.Id_card = idcard_cell.StringValue;
                    if (string.IsNullOrWhiteSpace(worker.Id_card))
                    {
                        return new Result("身份证号不可为空");
                    }
                    if (worker.Id_card.Length > 40)
                    {
                        return new Result("身份证号长度超限");
                    }

                    //手机号
                    var ph_cell = row_cells.GetCellOrNull(3);
                    if (ph_cell != null)
                    {
                        worker.Phone = ph_cell.StringValue;
                    }

                    //民族
                    var eb_cell = row_cells.GetCellOrNull(4);
                    if (eb_cell != null)
                    {
                        worker.Ethnic = eb_cell.StringValue;
                        List<string> minzu = MyConfigReader.GetConfigList("minzu");
                        if (minzu != null && minzu.Count > 0)
                        {
                            bool right2 = minzu.Any(x => x == worker.Ethnic);
                            if (!right2)
                            {
                                return new Result("民族数据不是有效值");
                            }
                        }
                    }

                    //工区/部门
                    var gh_cell = row_cells.GetCellOrNull(5);
                    if (gh_cell == null)
                    {
                        return new Result("工区/部门不可为空,行号:" + i);
                    }
                    worker.Department_id = gh_cell.StringValue.Trim();
                    if (string.IsNullOrWhiteSpace(worker.Department_id))
                    {
                        return new Result("工区/部门不可为空");
                    }

                    //检查部门id是否存在数据库,添加时间:2021-12-16 11:50:08
                    bool right= departmentDAL.Any(x=>x.Id == worker.Department_id);
                    if (!right)
                    {
                        return new Result("工区/部门值无效,无效值:"+ worker.Department_id);
                    }

                    //关联号
                    var work_no_cell = row_cells.GetCellOrNull(6);
                    if (work_no_cell == null)
                    {
                        return new Result("关联号不可为空,行号:" + i);
                    }
                    worker.Work_no = work_no_cell.StringValue;
                    bool rightNo = await workerDAL.AnyAsync(x => x.Work_no == worker.Work_no);
                    if (rightNo)
                    {
                        return new Result($"关联号{worker.Work_no}已存在,请修改,保证唯一");
                    }

                    //职务
                    var zw_cell = row_cells.GetCellOrNull(7);
                    if (zw_cell != null)
                    {
                        worker.Position = zw_cell.StringValue;
                    }

                    //职名
                    var zwm_cell = row_cells.GetCellOrNull(8);
                    if (zwm_cell != null)
                    {
                        worker.Job = zwm_cell.StringValue;
                    }

                    //技能等级
                    var jndj_cell = row_cells.GetCellOrNull(9);
                    if (jndj_cell != null)
                    {
                        worker.Skill_level = jndj_cell.StringValue;
                    }

                    //备注
                    var bz_cell = row_cells.GetCellOrNull(10);
                    if (bz_cell != null)
                    {
                        worker.Remark = bz_cell.StringValue;
                    }

                    list.Add(worker);
                    func($"第{i+1}行数据验证通过");
                }
                func("数据全部正确,准备保存...");
            }
            catch (Exception ex)
            {
                var ep = ex.InnerException ?? ex;
                return new Result("读取EXCEL文件异常:" + ep.Message);
            }
            finally
            {
                stream?.Close();
                stream?.Dispose();
            }
            func("保存处理中...");
            int count = await workerDAL.AddListAsync(list);
            if (count > 0)
            {
                func("保存成功");
                //记录操作日志                
                Operate_log operate_Log = new Operate_log();
                operate_Log.Operate_user_id = loginUserId;
                operate_Log.Operate_type = 5;
                operate_Log.Operate_content = "批量导入工人";
                //operate_Log.Old_data_id = projectId;
                operate_LogDAL.AddOperateLog(operate_Log);
                return new Result(true) { Data = list };
            }
            return new Result("导入工人失败");
        }
    }
}

你可能感兴趣的:(SignalR,asp.net,core,c#)