asp.net-web-apiasp.net-coreheadersignalr-hubasp.net-core-signalr

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?


Solution

  • 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.