C# 如何使用 SignalR 加入群组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17309745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:07:18  来源:igfitidea点击:

How to join a group using SignalR

c#javascriptsignalr

提问by user516883

I am new to using SignalR (started today), Pretty simple to send a message to ALL clients connected, but now I want to just send to a group. I cannot find simple documentation on how to join on the client side. If anyone can help, how can I SIMPLY join a group on the javascript side. Thanks for any help.

我是使用 SignalR 的新手(从今天开始),向所有连接的客户端发送消息非常简单,但现在我只想发送给一个组。我找不到有关如何在客户端加入的简单文档。如果有人可以提供帮助,我怎么能简单地加入 javascript 方面的一个组。谢谢你的帮助。

public class EventHub : Hub
{
    public void SendNewMedia(MediaInfoViewModel model,Guid eventId)
    {
        Clients.Group(eventId.ToString()).setupmedia(model);
    }
}
//Controller that is sending client new data
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
              var result = eventHub.Clients.Group(eventId.ToString()).setupmedia(eventViewer);

//Finally the javascript. Not sure how to setup just for a group
$(function () {
    var event = $.connection.eventHub;
    event.client.setupmedia = function (newMedia) {

        $('#photolist').prepend('<li><img src="' + newMedia.MediaUrl + '" class="img-polaroid span2"/></li>');
    };
    $.connection.hub.start(function() {
        event.server.create(eventID);//I know this is wrong but not sure how to connect
    }).done(function () {
        alert('conntected. Ready to retrieve data!');
    });
});

采纳答案by Nikola Dimitroff

You can't. If you could join a group from javascript then anyone may use your code to join any group which breaks security. If you really need to do that - create a method on the server side that takes a group name as parameter and adds the client to the group.

你不能。如果您可以从 javascript 加入一个组,那么任何人都可以使用您的代码加入任何破坏安全性的组。如果您确实需要这样做 - 在服务器端创建一个方法,该方法将组名作为参数并将客户端添加到组中。

public void JoinGroup(string groupName)
{
    this.Groups.Add(this.Context.ConnectionId, groupName);
}

Afterwards, call it from JS like that

之后,像这样从JS调用它

eventHub.server.joinGroup("my-awsm-group");

回答by JCisar

Just in case you come across this question now (like I did), here is an example for how to implement an azure function to support groups.

以防万一你现在遇到这个问题(就像我做的那样),这里有一个例子,说明如何实现一个 azure 函数来支持组。

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-signalr-service#2x-c-group-management-output-examples

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-signalr-service#2x-c-group-management-output-examples