I'm trying to pass userId to hub on connection to signalR. This is how client sets up the connection:
connection = new HubConnectionBuilder()
.WithUrl("http://localhost:56587/hub", options =>
{
options.Headers["UserId"] = loginTextBox.Text;
})
.AddMessagePackProtocol()
.Build();
How can I read this header in OnConnectedAsync() method in my hub?
SignalR Hubs are a way to logically group connections as documented. Take an example of a chat application. A group of users could be part of the same hub which allows for sending messages between users in the group. The hubName here can be any string which is used to scope messages being sent between clients.
ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack.
public async Task BroadcastToUser(string data, string userId) => await Clients. User(userId). SendAsync("broadcasttouser", data); Remember that when we are sending messages to a user, they will be sent to all connections associated with that user and not just any particular connection.
ASP.NET Core SignalR is a library that simplifies adding real-time web functionality to apps. It uses WebSockets whenever possible. For most applications, we recommend SignalR rather than raw WebSockets.
To get Header Value as string:
public override async Task OnConnectedAsync()
{
var httpCtx = Context.GetHttpContext();
var someHeaderValue = httpCtx.Request.Headers["UserId"].ToString();
}
Note - You may want to consider passing information in the query string however as not all transports support headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With