ASP.NET Core SignalR实时推送配置,业务层实时推送SignalR消息
Posted 棉晗榜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET Core SignalR实时推送配置,业务层实时推送SignalR消息相关的知识,希望对你有一定的参考价值。
web框架版本:.NET 6
不需要安装nuget有关signalr的包
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
/// <summary>
/// 消息推送集线器
/// </summary>
public class ChatHub : Microsoft.AspNetCore.SignalR.Hub
//public void Revice()
// Clients.All.SendAsync("ReceiveMessage", user, message);
//
添加SignalR的前端js文件
*.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
/// <summary>
/// 工人管理
/// </summary>
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
/// <summary>
/// 工人业务处理
/// </summary>
public interface IWorkBusiness
/// <summary>
/// 批量导入工人
/// </summary>
/// <param name="stream">excel文件流</param>
/// <param name="loginUserId">登录人id</param>
/// <param name="func">推送消息回调</param>
/// <returns></returns>
/// <remarks>
/// 创建时间:2021-12-9 17:42:08
/// </remarks>
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
/// <summary>
/// 获取工人,接口实现
/// </summary>
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;
/// <summary>
/// 批量导入工人
/// </summary>
/// <param name="stream">excel文件流</param>
/// <param name="loginUserId">登录人id</param>
/// <param name="func">推送消息回调</param>
/// <returns></returns>
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 (以上是关于ASP.NET Core SignalR实时推送配置,业务层实时推送SignalR消息的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core的实时库: SignalR简介及使用