如何使用SignalR检测来自同一台计算机的多个连接

时间:2014-09-19 13:43:21

标签: c# asp.net signalr

我的任务是开发一个实用程序,以便在我们的Web应用程序(会计系统同步等)中在用户计算机上运行任务。我使用SignalR与两端进行通信,效果很好。但是,我想添加一个验证,即应用程序在同一台计算机上运行,​​而不是从Web应用程序调用它的人。

到目前为止,我已经能够使用用户名进行验证。实用程序app通过SignalR将用户名传递到集线器,当我从Web应用程序调用它时,我可以验证用户名。

protected string CurrentEmployeeUsername
{
    get { return Context.User.Identity.Name; }
}

/// <summary>
/// Used to lock the dictionary for concurrent connections
/// </summary>
private static readonly object LockObject = new object();

private static Dictionary<string, string> _UtilityAppSessions;

/// <summary>
/// Keep a track of connectionId / username
/// </summary>
public static Dictionary<string, string> UtilityAppSessions
{
    get
    {
        return _UtilityAppSessions ??
               (_UtilityAppSessions = new Dictionary<string, string>());
    }
}

/// <summary>
/// Joins the group for the utility app
/// </summary>
public Task JoinUtilityAppGroup(string username)
{
    lock (LockObject)
    {
        UtilityAppSessions.Add(Context.ConnectionId, username.ToUpper());
    }

    return Groups.Add(Context.ConnectionId, "Utility");
}

public AccountingSyncronizationOperationResult ProcessSynchronization(SynchronizationOrigin origin, string synchronizationId)
{
    // Check if we have a utility app running
    if (!UtilityAppSessions.Any())
    {
        return new AccountingSyncronizationOperationResult()
        {
            Success = false,
            ErrorMessage = "No utility application is available to process the synchronization."
        };
    }

    // Make sure the user have the utility app running with their username
    if (UtilityAppSessions.ContainsValue(CurrentEmployeeUsername.ToUpper()))
    {
        // The user is running the utility app on his computer, start sync.
        Clients.Client(UtilityAppSessions.FirstOrDefault(x => x.Value == CurrentEmployeeUsername).Key).doSynchronization(new {Origin = origin, SynchronizationId = synchronizationId});

        return new AccountingSyncronizationOperationResult()
        {
            Success = true
        };
    }

    return new AccountingSyncronizationOperationResult()
    {
        Success = false,
        ErrorMessage = "The utility app needs to be running with your username and on your computer to process synchronization."
    };

}

这样可行,但是如果用户登录到另一台计算机,它将在运行它的计算机上调用该实用程序,而不是在Web应用程序所在的计算机上。 显然ConnectionIds是不同的(在Web应用程序和实用程序应用程序之间)因为我有两个不同的连接,所以除非我错过了一些不会帮助我的东西。

这应该不是我们的应用程序中的问题,因为每个人都应该拥有自己的用户名,但如果可以的话,我希望这个功能更加稳固。

感谢任何人的投入

0 个答案:

没有答案