Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read headers data in hub SignalR ASP.NET Core 2.1

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?

like image 808
Peace Avatar asked Aug 08 '18 14:08

Peace


People also ask

What is hubName in SignalR?

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.

Does SignalR use JSON?

ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack.

How do I send a message to particular client in SignalR?

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.

Does SignalR require WebSockets?

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.


1 Answers

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.

like image 134
ttugates Avatar answered Oct 19 '22 18:10

ttugates