SignalR - sending parameter to OnConnected?

Viewed 28301

I have the following JS working:

var chat = $.connection.appHub;

My app has a single hub, AppHub, that handles two types of notifications - Chat and Other. I'm using a single hub because I need access to all connections at all times.

I need to be able to tell OnConnected which type it is via something like the following:

[Authorize]
public class AppHub : Hub {
    private readonly static ConnectionMapping<string> _chatConnections =
        new ConnectionMapping<string>();
    private readonly static ConnectionMapping<string> _navbarConnections =
        new ConnectionMapping<string>();
    public override Task OnConnected(bool isChat) { // here
        string user = Context.User.Identity.Name;
        if (isChat){
            _chatConnections.Add(user, Context.ConnectionId);
            _navbarConnections.Add(user, Context.ConnectionId);
        } else{
            _navbarConnections.Add(user, Context.ConnectionId);
        }  
    }
}

Usage would ideally be something like this:

var chat = $.connection.appHub(true);

How can I pass that parameter to the hub from javascript?

Update:

SendMessage:

 // will have another for OtherMessage
 public void SendChatMessage(string who, ChatMessageViewModel message) {
        message.HtmlContent = _compiler.Transform(message.HtmlContent);
        foreach (var connectionId in _chatConnections.GetConnections(who)) {
            Clients.Client(connectionId).addChatMessage(JsonConvert.SerializeObject(message).SanitizeData());
        }
    }
2 Answers

Hallvar's answer is useful in most cases. But sometimes you could also use headers to send data to the OnConnected method.

Code example for Asp .Net Framework:

var myParameter = HttpContext.Current.Request.Headers["HeaderName"];

For .NET 5+ you may need Dependency Injection to access HttpContext, as shown here

Related