Neville Nazerane
Neville Nazerane

Reputation: 7019

using signalR .net core client

I have set up a signalR website .net core. My function in my hub is:

public async Task Notify(int id) {
    await Clients.All.InvokeAsync("Notified", id);
}

I have also tested this with the following js:

let connection = new signalR.HubConnection(myURL);

    connection.on('Notified', data => {
        console.log(4, data);
    });

    connection.start();

The js code seems to work fine and I see the log when I try connection.Invoke('Notify').

Now I have a console app that can needs to make the invoke. I am trying this in two ways and don't mind either solution: 1. A mvc controller within the signalR website that can take the id and invoke 'Notified'. 2. Use the client library Microsoft.AspNetCore.SignalR.Client in the console app.

The way 1 I have only done in classic asp.net like this:

GlobalHost.ConnectionManager.GetHubContext(hubName)

But couldn't find a way to do this in .net core.

Way 2 I have used the library and tried this so far:

var con = new HubConnectionBuilder();
con.WithUrl(myURL);      
var connection = con.Build();
connection.InvokeAsync("Notify",args[0]).Wait();

This is the closest I have come to create a connection in the same way as the js code. However this code throws a null pointer when calling connection.InvokeAsync. The connection object is not null. It seems to be an internal object that is null. According to the stack trace the exception is thrown when a MoveNext() function is internally called.

Upvotes: 0

Views: 2444

Answers (2)

Neville Nazerane
Neville Nazerane

Reputation: 7019

Well looks like both are not currently possible. As of now I just used a forced way which is hopefully temporary.

I have created and used the following base class for hubs:

public abstract class MyHub : Hub
{

    private static Dictionary<string, IHubClients> _clients = new Dictionary<string, IHubClients>();

    public override Task OnConnectedAsync()
    {
        var c = base.OnConnectedAsync();
        _clients.Remove(Name);
        _clients.Add(Name, Clients);
        return c;
    }

    public static IHubClients GetClients(string Name) {
        return _clients.GetValueOrDefault(Name);
    }
}

Upvotes: 1

Pawel
Pawel

Reputation: 31610

  1. GlobalHost is gone. You need to inject IHubContext<THub> like in this sample.

  2. This can be a bug in SignalR alpha1. Can you file an issue on https://github.com/aspnet/signalr and include a simplified repro?

Upvotes: 0

Related Questions