【问题标题】:Send Session Id to SignalR Core OnConnected method将会话 ID 发送到 SignalR Core OnConnected 方法
【发布时间】:2021-11-14 02:07:31
【问题描述】:

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

如何将它也添加到 sessionHub 请求中,由集线器中的 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 作为 Header 添加到请求中,结果相同:

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

【问题讨论】:

    标签: c# asp.net-core razor-pages asp.net-core-signalr


    【解决方案1】:

    创建连接时需要在 url 中输入 sessionid 值。 这样它就可以在所有的 hub 方法中访问 代码将如下所示:

    var connection = new signalR.HubConnectionBuilder()
            .withUrl("/sessionsHub/?sessionId=@Model.SessionId")
            .build();
    
           connection.start().then(function(){
           //ToDo
            }).catch(function (err) {
            console.log(err);
           });
    

    【讨论】:

    • 这确实是解决方案!很遗憾,它没有写在文档中......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多