programing

SignalR-(IUserIdProvider) * NEW 2.0.0 *을 사용하여 특정 사용자에게 메시지 보내기

nasanasas 2020. 9. 5. 10:02
반응형

SignalR-(IUserIdProvider) * NEW 2.0.0 *을 사용하여 특정 사용자에게 메시지 보내기


최신 버전의 Asp.Net SignalR에서는 "IUserIdProvider"인터페이스를 사용하여 특정 사용자에게 메시지를 보내는 새로운 방법이 추가되었습니다.

public interface IUserIdProvider
{
   string GetUserId(IRequest request);
}

public class MyHub : Hub
{
   public void Send(string userId, string message)
   {
      Clients.User(userId).send(message);
   }
}

내 질문은 내가 누구에게 내 메시지를 보내는 지 어떻게 알 수 있습니까? 이 새로운 방법에 대한 설명은 매우 피상적입니다. 그리고이 버그가 포함 된 SignalR 2.0.0의 성명서 초안은 컴파일되지 않습니다. 이 기능을 구현 한 사람이 있습니까?

추가 정보 : http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections#IUserIdProvider

포옹.


SignalR은 각 연결에 대한 ConnectionId를 제공합니다. 어떤 연결이 누구 (사용자)에게 속하는지 확인하려면 연결과 사용자 간의 매핑을 만들어야합니다. 이는 애플리케이션에서 사용자를 식별하는 방법에 따라 다릅니다.

SignalR 2.0에서는 IPrincipal.Identity.NameASP.NET 인증 중에 설정된 로그인 사용자 식별자 인 inbuilt를 사용하여 수행됩니다 .

그러나 Identity.Name을 사용하는 대신 다른 식별자를 사용하여 사용자와의 연결을 매핑해야 할 수 있습니다. 이를 위해이 새 공급자를 사용자 지정 구현과 함께 사용하여 사용자를 연결에 매핑 할 수 있습니다.

IUserIdProvider를 사용하여 SignalR 사용자를 연결에 매핑하는 예

응용 프로그램에서 a userId사용하여 각 사용자를 식별 한다고 가정 해 보겠습니다 . 이제 특정 사용자에게 메시지를 보내야합니다. 우리가 userId하고 message있지만, SignalR는 또한 우리의 사용자 ID와 연결 간의 매핑을 알고 있어야합니다.

이를 위해 먼저 다음을 구현하는 새 클래스를 만들어야합니다 IUserIdProvider.

public class CustomUserIdProvider : IUserIdProvider
{
     public string GetUserId(IRequest request)
    {
        // your logic to fetch a user identifier goes here.

        // for example:

        var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
        return userId.ToString();
    }
}

두 번째 단계는 SignalR에 CustomUserIdProvider기본 구현 대신 우리를 사용하도록 지시하는 것입니다. 허브 구성을 초기화하는 동안 Startup.cs에서 수행 할 수 있습니다.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var idProvider = new CustomUserIdProvider();

        GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);          

        // Any connection or hub wire up and configuration should go here
        app.MapSignalR();
    }
}

이제 다음 userId과 같이 문서에 언급 된대로 특정 사용자에게 메시지를 보낼 수 있습니다 .

public class MyHub : Hub
{
   public void Send(string userId, string message)
   {
      Clients.User(userId).send(message);
   }
}

도움이 되었기를 바랍니다.


여기 시작합니다 .. 제안 / 개선 사항을 엽니 다.

섬기는 사람

public class ChatHub : Hub
{
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        Clients.Group(name).addChatMessage(name, message);
        Clients.Group("2@2.com").addChatMessage(name, message);
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        Groups.Add(Context.ConnectionId, name);

        return base.OnConnected();
    }
}

자바 스크립트

( 위의 서버 코드에있는 방법 addChatMessagesendChatMessage방법에 주목하십시오 )

    $(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.addChatMessage = function (who, message) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(who).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page.
        $('#chat').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment.
            $('#message').val('').focus();
        });
    });
});

테스팅 enter image description here


다음은 공급자를 사용하지 않고 특정 사용자를 대상으로 지정하기 위해 SignarR을 사용하는 방법입니다.

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

기능 SignalR 테스트 를 참조하십시오.

테스트 "SendToUser"는 일반 owin 인증 라이브러리를 사용하여 전달 된 사용자 ID를 자동으로 가져옵니다.

The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.

참고URL : https://stackoverflow.com/questions/19522103/signalr-sending-a-message-to-a-specific-user-using-iuseridprovider-new-2-0

반응형