本文介绍了SignalR-从上下文调用静态类型的集线器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何从服务器上调用强类型集线器上的方法.我正在使用.Net-Core 2.0

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?

推荐答案

可以.这是逐步的示例:

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

从中心继承:

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

将类型化的hubcontext注入到控制器中,并对其进行处理:

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

这篇关于SignalR-从上下文调用静态类型的集线器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 03:54