2013-12-09 38 views
5

在SignalR中,我體驗到Context.User突然變爲空值,它有時也完全爲空,但這絕不應該發生,因爲只有授權用戶才能訪問集線器。Context.User在Signalr上更改爲null

這些奇怪行爲的原因是什麼?我上的Visual Studio 2013年

[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

你確定你不是在等待這兩條線之間的任何地方嗎? – SLaks

+0

@SLaks我不用在代碼中的任何地方等待。 – Freshblood

+0

您是否找到了解決方案?我面臨同樣的問題。我在這裏找到了一些有趣的東西 - http://forums.asp.net/t/1895487.aspx但它不幫助我 –

回答

-2

我用Context.ConnectionId我SignalR 2.0項目中使用SignalR 2.0 ASP.NET MVC 4,我非常滿意。

在這種情況下爲static stringstatic List存儲connid來存儲傳入的連接ID,因爲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(); 
    } 
} 
+0

請注意,使用靜態字段,特別是列表來存儲服務器端狀態是一個絕對可怕的建議,並且從來沒有人應該這樣做。數據庫,緩存,文件,各種各樣,但不是。 –

+0

是的,這只是一個可怕的想法 – 3dd

0

這種身份驗證方法不會造成(https://github.com/tugberkugurlu/SignalRSamples/tree/master/ConnectionMappingSample)上SignalR 2.0 Context.User.Identity.Name空值:

[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"); 
    } 

然而,我遇到Context.User空值使用MVC5身份時模型。

4

這證實了2.0.2

https://github.com/SignalR/SignalR/issues/2753

目前,它解決了,但不包括在官方發佈的bug。

的選項有:

  1. 使用永久框架或長輪詢(問題只發生在使用網絡套接字)從GitHub
  2. 採取代碼,並與修正建立自己的二進制文件中包括
  3. 等待2.0.3。應該在那裏解決。
+0

http://stackoverflow.com/a/21337672/827230禁用websockets。 – fabspro

+0

http://stackoverflow.com/a/9996047/827230 – fabspro

相關問題