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?
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.
SignalR provides an API for creating server-to-client remote procedure calls (RPC). The RPCs invoke functions on clients from server-side .
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" };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With