如何向Signal Core上针对.NET Core 2.0的所有客户端发送消息

时间:2017-11-04 16:05:49

标签: c# signalr signalr-hub asp.net-core-2.0

我正在使用signalR 1.0.0-alpha2-final,并希望向所有连接的客户端发送消息。

我使用this tutorial作为起点。

我的RulesHub继承自Hub:

[EnableCors("MyPolicy")]
public class RulesHub : Hub
{
    private readonly IRuleService _ruleService;

    public RulesHub(IRuleService ruleService)
    {
        _ruleService = ruleService;
    }

    public Task Send()
    {
        var rules = _ruleService.RulesMonitoring();
        return Clients.All.InvokeAsync("SendRules", rules);
    }
}

在前端,我有这段代码才能连接到Hub:

let connection = new signalR.HubConnection(rulesMonitorUrl);

connection.on('SendRules', function(data:any){
    console.log(data);
});

连接一个客户端后,我从这个控制器调用Send方法:

[EnableCors("MyPolicy")]
Route("api/[controller]")]
public class MyController : Controller
{
    private readonly IMyService _myService;
    private RulesHub _rulesHub;

    public MyController(IMyService myService, IRuleService ruleService)
    {
        _myService = myService;
        _rulesHub = new RulesHub(ruleService);
    }

    [HttpPost]
    public void Post([FromBody]MyClass myClass)
    {
        _myService.Add(myClass);
        _rulesHub.Send();
    }
}

但是行return Clients.All.InvokeAsync("SendRules", rules);失败,出现以下异常消息:

  

System.NullReferenceException:'对象引用未设置为   一个对象的实例。'

     

Microsoft.AspNetCore.SignalR.Hub.Clients.get返回null。

我已经读过,在ASP.NET中你应该使用像IHubContext context = GlobalHost.ConnectionManager.GetHubContext("MyChatHub");这样的东西,但这不适用于这个版本。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

这是一个重复的问题: Call SignalR Core Hub method from Controller

您永远不应该自己停止集线器的实例。简单地将它注入您的控制器,如:

[EnableCors("MyPolicy")]
Route("api/[controller]")]
public class MyController : Controller
{
    private readonly IMyService _myService;
    private  IHubContext<RulesHub> _rulesHubContext;    

    public MyController(IMyService myService, IRuleService ruleService, IHubContext<RulesHub > rulesHubContext)
    {
        _myService = myService;
        _rulesHubContext = rulesHubContext;
    }

    [HttpPost]
    public void Post([FromBody]MyClass myClass)
    {
        _myService.Add(myClass);
        // Load your rules from somewhere 
        _rulesHubContext.Clients.All.InvokeAsync("SendRules", rules);
    }
}