2013-08-16 17 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(); 
    } 
};