简体   繁体   中英

How to send a message to all clients on SignalR alpha for NET Core 2.0

I'm using signalR 1.0.0-alpha2-final and want to send a message to all connected clients.

I have used this tutorial as a starting point.

I have my RulesHub that inherits from 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);
    }
}

On the frontend I have this code in order to connect to the Hub:

let connection = new signalR.HubConnection(rulesMonitorUrl);

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

And after connecting one client, I'm calling the Send method from this controller:

[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();
    }
}

But the line return Clients.All.InvokeAsync("SendRules", rules); is failing with the following exception message:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Microsoft.AspNetCore.SignalR.Hub.Clients.get returned null.

I have read that in ASP.NET you should use something like IHubContext context = GlobalHost.ConnectionManager.GetHubContext("MyChatHub"); but this is not working on this version.

Any ideas?

This is a duplicate question: Call SignalR Core Hub method from Controller

You should never ceate an instance of a hub by yourself. Simple inject it into your controller like:

[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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM