0

I am trying to implement a small demo in sample chat application.

I'm using SignalR in an ASP.NET MVC5 application, but found some problem while sending a message to specific/single client.

public class ChatHub : Hub
{
        string connectionId = "";     

        public string GetConnectionId()
        {
            return connectionId;
        }
        
        public override Task OnConnected()
        {
            connectionId = Context.ConnectionId;        
            return base.OnConnected();
        }
}

public class Common
{   
        public static void Send(string name, string message,string connectionId)
        {     
            IHubContext Context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();       
            Context.Clients.Client(connectionId).addNewMessageToPage(name, message);
        }           
}

I don't want to make following as static

public string GetConnectionId()
{
    return connectionId;
}

Then how can I send the connectionId to

Common.Send(name, message, connectionId)

which is being called in an ASP.NET MVC controller.

Is there any better suggestion/recommendation ?

Application built with ASP.NET MVC 5 with SignalR 2.4.1.

I am using this link for my demo application. You can see all details related to source code is at https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

Output: I tried to follow guides and looked up example implementations but could not solve the issue.

Mostly people are saying you can't do it by using GetHubContext

See it

https://github.com/aspnet/SignalR/issues/2274#issuecomment-389227033 https://github.com/aspnet/SignalR/issues/2274#issuecomment-389013456 Connection ID when calling SignalR Core Hub method from Controller

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
maifs
  • 1,061
  • 6
  • 15
  • 31
  • 1
    I would recommend using groups to join your users in to the "chatGroups" and send messages to the groups. You can see this github for example chat implementation with groups. https://github.com/Kiril1512/SignalRDemo/blob/master/Server/Hubs/SignalRHub.cs – Kiril1512 Oct 26 '20 at 18:08
  • OK I 'll check it and inform you asap – maifs Oct 27 '20 at 15:35

0 Answers0