在SignalR中,我体验到Context.User突然变成了空值,并且它有时完全为空,但这绝不应该发生,因为只有授权用户才能访问集线器。
这些奇怪行为的原因是什么?我在Visual Studio 2013上使用SignalR 2.0和ASP.NET MVC 4。
[Authorize]
public class FeedHub : Hub
{
public override Task OnConnected()
{
var name = Context.User.Identity.Name;// here is User is not null
var user = GetUser();// but it is changing to null inside this private method
return base.OnConnected();
}
private User GetUser()
{
var name = Context.User.Identity.Name;// here is User property is null and throws exception
return null;//
}
public override Task OnDisconnected()
{
//In here Context.User property is sometimes null but in my opinion this should never be null
// because Hub is protected by Authorize attribute.
return base.OnDisconnected();
}
}
答案 0 :(得分:4)
这是2.0.2中确认的错误
https://github.com/SignalR/SignalR/issues/2753
目前已解决,但尚未包含在官方发布中。
您的选择是:
答案 1 :(得分:0)
此身份验证方法不会导致SignalR 2.0(https://github.com/tugberkugurlu/SignalRSamples/tree/master/ConnectionMappingSample)上的Context.User.Identity.Name null值:
[HttpPost]
[ActionName("Login")]
public ActionResult PostLogin(LoginModel loginModel) {
if (ModelState.IsValid) {
FormsAuthentication.SetAuthCookie(loginModel.Name, true);
return RedirectToAction("index", "home");
}
return View(loginModel);
}
[HttpPost]
[ActionName("SignOut")]
public ActionResult PostSignOut() {
FormsAuthentication.SignOut();
return RedirectToAction("index", "home");
}
但是,在使用MVC5身份模型时,我确实遇到了Context.User null值。
答案 2 :(得分:-2)
我使用Context.ConnectionId
作为我的SignalR 2.0项目,我对它非常满意。
在这种情况下为static string
存储connid,或者存储传入连接ID的static List
,因为http是无状态的,每次回发都会删除信息。
public class FeedHub : Hub
{
static string username = "";
public override Task OnConnected() //event to fire whenever someone joins
{
var name = Context.ConnectionId;//capture the unique incoming connection id
var username = name;//write it into the static string
return base.OnConnected();
}
public override Task OnDisconnected() //event to fire whenever someone quits
{
//In here Context.User property is sometimes null because you only recognize authorized users.
return base.OnDisconnected();
}
}