Home > OS >  Send Session Id to SignalR Core OnConnected method
Send Session Id to SignalR Core OnConnected method

Time:09-22

I am trying to send the Session Id of an ASP.NET Core 5 application using Razor Pages to my SignalR Core Hub. However, the Session Id is only added to the negotiate request, not to the actual WebSocket that is being opened:

requests

How can I add it to the sessionsHub request as well, which is used by the OnConnected() method in the hub?

The Razor Page .cs:

public class IndexModel : PageModel
{
    private readonly HttpContext _httpContext;
    public string SessionId { get; set; }
    public IndexModel(IHttpContextAccessor httpContextAccessor)
    {

        _httpContext = httpContextAccessor.HttpContext;
    }
    public async Task OnGet()
    {
        SessionId = _httpContext.Session.Id;
    }
}

The .cshtml using a querystring, I've also tried adding a Session-Id as Header to the request, same result:

@page
@model IndexModel
<script type="text/javascript">
    var sessionId = "@Model.SessionId";
class CustomHttpClient extends signalR.DefaultHttpClient {
    send(request) {
        var url = new URL(request.url);
        if(!url.search){
            url.href = url.href   '?sessionId="'   sessionId   '"';
        }else{
            url.href = url.href   '&sessionId="'   sessionId   '"';
        }
        request.url = url.href;
        return super.send(request);
    }
}
var connection = new signalR.HubConnectionBuilder().withUrl("/sessionsHub", { httpClient: new CustomHttpClient() }).build();
connection.start().then(() => {
}).catch(function (err) {
    return console.error(err.toString());
});
</script>

The hub:

public class SessionHub : Hub{

    public override async Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
            
        string sessionId = GetSessionId();
    }

    private string GetSessionId()
    {
        HttpContext httpContext = Context.GetHttpContext();
        List<StringValues> sessionIdQueryString = httpContext.Request.Query.Where(x => x.Key == "sessionId").Select(x => x.Value).ToList();
        if (sessionIdQueryString.Count == 0)
        {
            throw new NullReferenceException();
        }

        string sessionId = sessionIdQueryString.First();
        
return sessionId;
    }
}

CodePudding user response:

You need to enter the sessionid value inside the url when creating the connetion. so that it can be accessed in all hub methods The code will look like this :

var connection = new signalR.HubConnectionBuilder()
        .withUrl("/sessionsHub/[email protected]")
        .build();

       connection.start().then(function(){
       //ToDo
        }).catch(function (err) {
        console.log(err);
       });
  • Related