Asp.Net Core SignalR获取集线器实例,从集线器外部发送消息
https://blog.csdn.net/u011127019/article/details/90812008
一、从控制器中获取IHubContext 操作发送消息
此种方式,常用简单
public class HomeController : Controller
{
private readonly IHubContext<NotificationHub> _hubContext;
public HomeController(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
}
public async Task<IActionResult> Index()
{
await _hubContext.Clients.All.SendAsync("Notify", $"Home page loaded at: {DateTime.Now}");
return View();
}
二、从中间件中获取IHubContext 操作发送消息
访问IHubContext中间件管道中如下所示:
app.Use(async (context, next) =>
{
var hubContext = context.RequestServices
.GetRequiredService<IHubContext<MyHub>>();
//...
});
三、从定时任务/从非Http请求中 获取IHubContext
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor accessor)
{
MvcContext.Accessor = accessor;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
//配置SignalR
app.UseSignalR(routes => routes.MapHub<CountHub>("/count"));
//启动定时任务
Task.Run(() =>
{
while (true)
{
var hubContext = app.ApplicationServices
.GetService<IHubContext<CountHub>>();
hubContext.Clients.All.SendAsync("someFunc", new { random = "定时任务" });
Thread.Sleep(1000);
}
});
}
四、从请求上下文中获取IHubContext 实例,此方式同控制器
public class MvcContext
{
public static IHttpContextAccessor Accessor;
public static HttpContext GetContext()
{
return Accessor.HttpContext;
}
}
public class HubOperate
{
public IHubContext<CountHub> GetHubOne()
{
return MvcContext.GetContext()
.RequestServices
.GetRequiredService<IHubContext<CountHub>>();
}
}
测试代码:
[Route("test1/{action}")]
public class Test1Controller : Controller
{
public IActionResult One()
{
HubOperate _hub = new HubOperate();
_hub.GetHubOne().Clients.All.SendAsync("someFunc", new { random = "efgh" });
return Content("执行完成");
}
}