首页 > 解决方案 > C# 类中的 SignalR Hub

问题描述

请告诉我如何在非控制器类中使用 SignalR。我正在使用 AspNetCore.SignalR 1.0.2。

例如我的集线器:

public class EntryPointHub : Hub
{        
    public async Task Sended(string data)
    {
       await this.Clients.All.SendAsync("Send", data);
    }  
}

在我的工作课程(hangfire)中,SignalR 不起作用,我的前端没有收到消息。

public class UpdateJob
{
    private readonly IHubContext<EntryPointHub> _hubContext;

    public UpdateJob(IHubContext<EntryPointHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public void Run()
    {
        _hubContext.Clients.All.SendAsync("Send", "12321");
    }        
}

但它在我的控制器中运行良好。

...
public class SimpleController: Controller
{
    private readonly IHubContext<EntryPointHub> _hubContext;        

    public SimpleController(IHubContext<EntryPointHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpGet("sendtoall/{message}")]
    public void SendToAll(string message)
    {
        _hubContext.Clients.All.SendAsync("Send", message);
    }        
}

标签: asp.netasp.net-coresignalr

解决方案


我认为您的作业类缺少 .net 核心 DI 机制。在 Startup.cs 文件中添加如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddScoped<UpdateJob>();
}
public void Configure(IApplicationBuilder app)
    {
        app.UseSignalR(routes =>
        {
            routes.MapHub<EntryPointHub>("ephub");
        });
    }

然后你需要为客户端安装 signalr-client 并在 js 文件中调用如下所示。

let connection = new signalR.HubConnection('/ephub');
connection.on('send', data => {
    var DisplayMessagesDiv = document.getElementById("DisplayMessages");
    DisplayMessagesDiv.innerHTML += "<br/>" + data;
});

希望这会帮助你。


推荐阅读