asp.net - 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);
}
}
解决方案
我认为您的作业类缺少 .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;
});
希望这会帮助你。
推荐阅读
- azure - 包含脚本任务的 SSIS 包在 Azure 数据工厂中失败
- angular - 更改用户名应在所有其他页面中生效
- postgresql - Postgresql 枚举比较不适用于一种特定类型
- jquery - 如何在下拉列表中仅处于活动状态时更改特定项目的颜色
- python - Python:如何为表示函数的实例变量编写单元测试?
- audiounit - AVAudioEnvironmentNode 在后台模式下更改其渲染算法时崩溃
- javascript - 如何在没有召回服务的情况下将相同的数据使用到另一个页面?
- python - 如何使用 tkinter 每十秒将数据收集到同一个 CSV 文件中
- php - 要求在文件夹中找到所有块(而不是将它们全部写出来)
- macos - Running Docker containers slows down new Macbook Pro to a crawl