2013-08-16 18 views
1

我有一個類繼承PersistentConnection。當我覆蓋OnConnected時,我檢查了一些傳入的查詢字符串參數,以確保用戶已通過身份驗證。如果沒有,我會拋出一個異常,但客戶端仍然被認爲是連接的。我如何從連接的客戶列表中刪除客戶端?OnConnected引發異常 - 我如何刪除連接?

public class NotificationConnection : PersistentConnection 
{ 
    protected override Task OnConnected(IRequest request, string connectionId) 
    { 
     if (String.IsNullOrWhiteSpace(request.QueryString["example"])) 
      throw new SecurityException("whatever"); 

     return base.OnConnected(request, connectionId); 
    } 

    protected override Task OnDisconnected(IRequest request, string connectionId) 
    {    
     return base.OnDisconnected(request, connectionId); 
    } 
} 

回答

2

考慮更改設計使用由signalr露出來驗證用戶的方法進行身份驗證,他們對永久連接權利

protected override bool AuthorizeRequest(IRequest request) 
    { 
     return request.User != null && request.User.Identity.IsAuthenticated; 
    } 
1

爲什麼不直接發送消息給客戶端,告訴它斷開連接?例如

在服務器上。

if (String.IsNullOrWhiteSpace(request.QueryString["example"])) 
{ 
    Connection.Send(connectionId, "Close"); 
} 

然後在JS客戶端上做類似的事情;

connection.received(function(data) { 
    if (data === "Close"){ 
     connection.stop(); 
     // send the user to another page with window.location or warn them that their connection has been stopped. 
    } 
}); 

在.net客戶端上;

connection.Received += data => 
{ 
    if (data == "Close") 
    { 
     connection.stop(); 
    } 
};