将会话 ID 发送到 SignalR Core OnConnected 方法

Send Session Id to SignalR Core OnConnected method

我正在尝试将使用 Razor Pages 的 ASP.NET Core 5 应用程序的会话 ID 发送到我的 SignalR Core Hub。但是,Session Id只是添加到协商请求中,并没有添加到实际打开的WebSocket中:

如何将它也添加到 sessionsHub 请求中,它由集线器中的 OnConnected() 方法使用?

剃刀页面 .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;
    }
}

使用查询字符串的 .cshtml,我也尝试将 Session-Id 作为请求头添加到请求中,结果相同:

@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>

枢纽:

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;
    }
}

创建连接时需要在url中输入会话ID值。 这样它就可以在所有集线器方法中访问代码将如下所示:

var connection = new signalR.HubConnectionBuilder()
        .withUrl("/sessionsHub/?sessionId=@Model.SessionId")
        .build();

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