Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR - Call statically typed hub from Context

I'm trying to figure out how to invoke a method on a strongly typed hub from the server. I'm using .Net-Core 2.0

I have a stongly typed hub interface:

public interface IMessageHub
{
    Task Create(Message message);
}

and a hub which looks like so:

public class MessageHub: Hub<IMessageHub>
{
    public async Task Create(Message message)
    {
        await Clients.All.Create(message);       
    }
}

Normally on the server I might push content to the client like so:

[Route("api/[controller]")]
public MessagesController : Controller
{
       IHubContext<MessagesHub> context;
       public MessagesController(IHubContext<MessagesHub> context)
       {
           this.context = context;
       }

       public Message CreateMessage(Message message)
       {
          this.context.Clients.All.InvokeAsync("Create", message);
          return message;
       }
}

How can I invoke a method on the statically typed hub or do I have a misconception on how hubs work?

like image 873
johnny 5 Avatar asked Nov 30 '17 03:11

johnny 5


People also ask

How do I send client specific messages using SignalR?

We change the BroadcastChartData() method to accept connectionId as an additional parameter. This way, we can find the client using the connectionId and send a message just to that client. Additionally, we add a new GetConnectionId() method, which returns the connectionId of the client.

Is SignalR an RPC?

SignalR provides an API for creating server-to-client remote procedure calls (RPC). The RPCs invoke functions on clients from server-side .


1 Answers

Yes you can. Here is the sample step by step:

Simple create an interface where you define which methods your server can call on the clients:

public interface ITypedHubClient
  {
    Task BroadcastMessage(string name, string message);
  }

Inherit from Hub:

 public class ChatHub : Hub<ITypedHubClient>
      {
        public void Send(string name, string message)
        {
          Clients.All.BroadcastMessage(name, message);
        }
      }

Inject your the typed hubcontext into your controller, and work with it:

[Route("api/demo")]
  public class DemoController : Controller
  {   
    IHubContext<ChatHub, ITypedHubClient> _chatHubContext;
    public DemoController(IHubContext<ChatHub, ITypedHubClient> chatHubContext)
    {
      _chatHubContext = chatHubContext;
    }
    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
      _chatHubContext.Clients.All.BroadcastMessage("test", "test");
      return new string[] { "value1", "value2" };
    }
  }
like image 123
Stephu Avatar answered Sep 24 '22 04:09

Stephu