StartUp上的SignalR和数据库通信失败

时间:2016-10-24 07:23:48

标签: c# asp.net-mvc asp.net-mvc-5 signalr

在建立集线器连接的网站中,我调用服务器端函数来记录数据库中的用户信息。数据库中的表用于跟踪用户连接/断开状态。我注意到用户并不总是显示为已连接。因此,我认为是因为没有写入表格。我查了一下,没有行...

我添加了ErrorHandlingPipeline来捕获错误。我得到的只是Object reference not set to an instance of an object。似乎产生错误的函数是我在启动连接时调用的第一个函数,如前所述。这是:

public async Task Join()
{
   var user      = GetUser(Context.User.Identity.Name);
   var groupName = user.Group;

   await Groups.Add(Context.ConnectionId, groupName);
   Clients.Group(groupName).addUser(Context.User.Identity.Name);

   // Update group in the db
   using (var db = new UserEntities())
   {
      var connection = db.OnlineUsers.Find(Context.ConnectionId);
      connection.Group = groupName;
      db.SaveChanges();
   }
}

我还在public override Task OnConnected()中放置了一个断点,但似乎首先调用了Join()?因为它没有停在那一个。 我认为,这就是问题,但为什么OnConnected先不会被调用呢?

这是枢纽:

   $.connection.hub.start().done(function () {
       // connected
       theHub.server.join();
   });

更新 看起来问题可能出在IE11上,它适用于FireFox和Chrome。这是来自IE的控制台日志:

SignalR: webSockets transport starting.
SignalR: Connecting to websocket endpoint 'ws://localhost:1234/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=1234%3connectionData=%a%b&tid=1'.
SignalR: Websocket opened.
SignalR: webSockets transport connected. Initiating start request.
SignalR: The start request succeeded. Transitioning to the connected state.
SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332, keep alive timeout of 20000 and disconnecting timeout of 30000
SignalR: Invoking MyHub.Join
SignalR: Triggering client hub event 'addUser' on hub 'MyHub'.
SignalR: MyHub.Join failed to execute. Error: There was an error invoking Hub method 'MyHub.Join'.
SignalR: Triggering client hub event 'addUser' on hub 'MyHub'.
[SignalR: Triggering client hub event 'addUser' on hub 'MyHub'.
SignalR: Invoking MyHub.GetaddUser

1 个答案:

答案 0 :(得分:0)

订阅集线器时将调用您的OnConnected,如果没有订阅,OnConnected将不会被激活。您似乎没有订阅集线器。

这个问题可能会有所帮助

OnConnected method not called SignalR when I use shared connection in multiple hubs

以下是一些从JQuery连接和订阅集线器的示例代码

C#Hub

[HubName("YourHubName")]
public class YourHubName : Hub
{
    [HubMethodName("Subscribe")]
    public void Subscribe(string groupId)
    {                       
        Groups.Add(Context.ConnectionId, groupId);

        Clients.Group(groupId).addMessageToPage("Sucessfully subscribed to group : " + groupId);
    }
}

这是JQuery

var connection = null;
var hub = null;

function initializeHub(signalRServer)
{
    connection = $.hubConnection(signalRServer);
    hub = connection.createHubProxy('YourHubName');
}

function subscribeToHub(groupId)
{
    try
    {
        connection.start(
        { 
            transport: ['webSockets', 'longPolling'], 
            withCredentials: false 
        })
        .done(function ()
        {
            hub.invoke('Subscribe',groupId)
                .done(function () {                
                    console.log("Subscribed");
                })
                .fail(function (error) {
                    console.log('Failed to subscribe');
                });
        })
        .fail(function (error)
        {
            console.log("An error occured with signarR connection : " + error);
        });   

        /*Declared the addMessageToPage method which SignalR will push to*/
        hub.on('addMessageToPage', function (message) {
            console.log("Message received from SignalR server : " + message);
        });         
    }
    catch (e) {
        console.log("An error occured with subscription process");
    }
}

然后,在调用Hub的页面中

$(document).ready(function () {
    initializeHub("YourSignalRUrlHere"]");
}

如果您想触发对集线器的订阅,请致电

subscribeToHub("HubGroupId");