SignalR - 呼叫一个组的成员不工作

时间:2016-02-02 16:32:36

标签: asp.net-core signalr-hub

上下文

我正在将SignalR 3 RC1与ASP.NET 5用于我的项目,我无法让我的客户端订阅特定组,以便从我的服务器接收消息。

集线器类

[HubName("ChatHub")]
public class ChatHub : Hub
{
   public async Task Join(string userId)
   {
      if (!string.IsNullOrEmpty(userId))
      {
          await Groups.Add(Context.ConnectionId, userId);
      }
   }
}

JS代码

var chatHub = hubConnection.createHubProxy("chatHub");
    chatHub .on("newMessage", (response) => {
        console.log(response);
    });

    hubConnection.start().done(response => {
        chatHub.invoke("join", "userid");
    });

的WebAPI

public class ChatController : ApiController
{
    protected readonly IHubContext ChatHub;

    public ChatController(IConnectionManager signalRConnectionManager)
    {
        ChatHub = signalRConnectionManager.GetHubContext<ChatHub>();
    }

    [Authorize]
    [HttpPost]
    [Route("Message")]
    public async Task<IActionResult> CreateMessage([FromBody] messageParams dto)
    {
        await ChatHub.Clients.Group("userid").NewMessage("hello world");
    }
}

如果我播放“所有”客户端,它正在工作。

await ChatHub.Clients.All.NewMessage("hello world");

是否有特定配置将消息广播到特定组?

1 个答案:

答案 0 :(得分:2)

对于有兴趣使用ASP.NET 5和Signalr 2.2的人,我在IAppBuilder和IApplicationBuilder之间创建了一个桥梁

internal static class IApplicationBuilderExtensions
    {
        public static void UseOwin(
          this IApplicationBuilder app,
          Action<IAppBuilder> owinConfiguration)
        {
            app.UseOwin(
              addToPipeline =>
              {
                  addToPipeline(
                    next =>
                    {
                        var builder = new AppBuilder();

                        owinConfiguration(builder);

                        builder.Run(ctx => next(ctx.Environment));

                        Func<IDictionary<string, object>, Task> appFunc =
                          (Func<IDictionary<string, object>, Task>)
                          builder.Build(typeof(Func<IDictionary<string, object>, Task>));

                        return appFunc;
                    });
              });
        }
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
            app.UseOwin(owin => owin.MapSignalR());
}

导入这些依赖项

"Microsoft.AspNet.Owin": "1.0.0-rc1-final",
"Microsoft.Owin": "3.0.1"