Asp.Net Core SignalR获取集线器实例,从集线器外部发送消息

一、从控制器中获取IHubContext 操作发送消息

此种方式,常用简单

public class HomeController : Controller
{
    private readonly IHubContext _hubContext;

    public HomeController(IHubContext hubContext)
    {
        _hubContext = hubContext;
    }
}
public async Task 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>();
    //...
});

三、从定时任务/从非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("/count"));

    //启动定时任务
    Task.Run(() =>
    {
        while (true)
        {
            var hubContext = app.ApplicationServices
            .GetService>();
            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 GetHubOne()
        {
            return MvcContext.GetContext()
                 .RequestServices
                 .GetRequiredService>();
        }
    }

测试代码:

    [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("执行完成");
        }
    }

如何全局获取上下文:Asp.Net Core获取请求上下文HttpContext

 

更多:

 Asp.Net Core 2.0使用SignalR技术-入门

 Asp.Net Core WebSocket绑定

SingalR自托管(self-host)实例2-实现Wpf客户端和Web客户端矩形同步

你可能感兴趣的:(Asp.net,SignalR)