SignalR - Call statically typed hub from Context

落花浮王杯 提交于 2021-02-19 01:37:05

问题


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?


回答1:


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" };
    }
  }



回答2:


so the send method in ChatHub is not really relevant in the example. in fact, just define the method in ITypedHubClient and no implementation is required, correct? singalR will magically translate the call on the server side as SendAsync('BroadcastMessage', blah blah)



来源:https://stackoverflow.com/questions/47565576/signalr-call-statically-typed-hub-from-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!