在 SignalR Hub 中验证用户时 GetHttpContext() null

GetHttpContext() null while authenticating user in SignalR Hub

我正尝试在 SignalR Hub 中使用 Asp.Net 身份创建和登录用户,如下所示:

public string CreateUser(string username, string password)
{
    var userStore = new UserStore<IdentityUser>();
    var manager = new UserManager<IdentityUser>(userStore);

    var user = new IdentityUser() { UserName = username };
    IdentityResult result = manager.Create(user, password);

    if (result.Succeeded)
    {
        var authenticationManager = Context.Request.GetHttpContext().GetOwinContext().Authentication;
        var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
        authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
        return "Success";
    }
    else
    {
        var authenticationManager = Context.Request.GetHttpContext().GetOwinContext().Authentication;
        return "Failed: "+result.Errors;
    }
}

但是 GetHttpContext() 始终为 null,有人可以解释一下原因吗?

从 Hub 中调用 SignIn 方法的最佳方式是什么?

老问题了,但是集线器是一个开放的通信渠道,所以像这样使用表单身份验证和身份的过程是行不通的。没有关于设置 headers 的响应或设置 cookie 的方法。为此,您需要定期进行 HTTP 交换。