c# - Signalr 未在 Azure 主机上发送数据

标签 c# azure signalr

我正在开发一个网络应用程序,我在特定页面上使用两个集线器将通知从服务器推送到客户端并处理客户端之间的消息。但是,我在 Azure 生产应用服务中遇到了一种情况,其中通知中心不会将数据传输回客户端,即使查询带来了正确的数据。

客户端代码:

// Declare a proxy to reference the hub.
var notifHub = $.connection.NotificationHub;
var chat = $.connection.ChatHub;
var maxTabs = 10, index = 1;

// Start the connection.
$.connection.hub.start().done(function () {
    notifHub.server.getNotifications();

    /* Some more code irrelevant to this question */
});

notifHub.client.getNotifications = function (notification) {
    // Html encode display name and message.
    const notifications = JSON.parse(notification);
    // Add the message to the page.

    $("#Notifications").empty();

    notifications.forEach(function (notification) {

        const notificationDate = new Date(notification.CreationDate);
        let alertColor = "";

        if (((new Date) - notificationDate) < oneMinute)
            alertColor = "alert-success";
        else if (((new Date) - notificationDate) > oneMinute &&
            ((new Date) - notificationDate) < fiveMinutes)
            alertColor = "alert-warning";
        else if (((new Date) - notificationDate) > fiveMinutes)
            alertColor = "alert-danger";

        //language=html
        var notificationTemplate = "<div class ='alert " + alertColor + "' role='alert' data-request-id='{{RequestId}}' data-connection-id='{{ConnectionId}}' data-requester='{{RequesterName}}' data-group-name='{{RequesterGroup}}' data-request-date-time='{{CreationDate}}'><strong>Usuario</strong>: {{RequesterName}}<br /><strong>Fecha</strong>: {{CreationDate | datetime}}</div>";

        $("#Notifications").append(Mustache.render(notificationTemplate, notification));
    });
};

中心代码

public void GetNotifications()
{
    var db = new Entities();

    db.Database.Log = s => Debug.WriteLine(s);

    var companyId = Context.User.Identity.GetCompanyId();

    var notifications = (from notification in db.AgentRequestNotification
                             where notification.AttendedByAgent == false && notification.CompanyId == companyId
                             orderby notification.CreationDate 
                             select notification).ToList();

        Clients.All.getNotifications(JsonConvert.SerializeObject(notifications));
}

代码在我的本地环境中完美运行,如下面的屏幕截图所示

Local environment

但不适用于生产环境

enter image description here

在我的 Azure 应用程序设置中,我启用了 Websockets 并禁用了 ARR Affinity。我有 使用 VS 远程调试,这是我得到的输出,不确定 EF 查询日志后显示的 WebSocketException 的原因是什么

      Opened connection at 1/15/2018 9:03:46 PM +00:00

SELECT 
    [Project1].[RequestId] AS [RequestId], 
    [Project1].[ConnectionId] AS [ConnectionId], 
    [Project1].[RequesterName] AS [RequesterName], 
    [Project1].[RequesterGroup] AS [RequesterGroup], 
    [Project1].[AttendedByAgent] AS [AttendedByAgent], 
    [Project1].[CreationDate] AS [CreationDate], 
    [Project1].[CompanyId] AS [CompanyId], 
    [Project1].[AttendedByAgentDate] AS [AttendedByAgentDate]
    FROM ( SELECT 
        [Extent1].[RequestId] AS [RequestId], 
        [Extent1].[ConnectionId] AS [ConnectionId], 
        [Extent1].[RequesterName] AS [RequesterName], 
        [Extent1].[RequesterGroup] AS [RequesterGroup], 
        [Extent1].[AttendedByAgent] AS [AttendedByAgent], 
        [Extent1].[CreationDate] AS [CreationDate], 
        [Extent1].[CompanyId] AS [CompanyId], 
        [Extent1].[AttendedByAgentDate] AS [AttendedByAgentDate]
        FROM [dbo].[AgentRequestNotification] AS [Extent1]
        WHERE (0 = [Extent1].[AttendedByAgent]) AND ([Extent1].[CompanyId] = @p__linq__0)
    )  AS [Project1]
    ORDER BY [Project1].[CreationDate] ASC


-- p__linq__0: '1' (Type = Int32, IsNullable = false)

-- Executing at 1/15/2018 9:03:49 PM +00:00

-- Completed in 25 ms with result: SqlDataReader



Closed connection at 1/15/2018 9:03:49 PM +00:00

The thread 0x1520 has exited with code 0 (0x0).
The thread 0x2904 has exited with code 0 (0x0).
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Web.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Web.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in mscorlib.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll
Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
w3wp.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x800704CD): An operation was attempted on a nonexistent network connection
   at System.Web.WebSockets.WebSocketPipe.<>c__DisplayClass8_0.<WriteCloseFragmentAsync>b__0(Int32 hrError, Int32 cbIO, Boolean fUtf8Encoded, Boolean fFinalFragment, Boolean fClose)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass46_0.<<DoWork>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.WebSockets.AspNetWebSocket.<DoWork>d__45`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass32_0.<<CloseOutputAsyncImpl>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<>c.<<CloseAsync>b__13_0>d.MoveNext()
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.SqlServer.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in Microsoft.Owin.Security.Cookies.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll
Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in Microsoft.Owin.Host.SystemWeb.dll
The thread 0x219c has exited with code 0 (0x0).

这是 SignalR 客户端日志

[17:56:53 GMT-0500 (Eastern Standard Time)] SignalR: No hubs have been     subscribed to.  The client will not receive data from hubs.  To fix, declare at     least one client side function prior to connection start for each hub you wish     to subscribe to.
[17:56:53 GMT-0500 (Eastern Standard Time)]     ignalR: Negotiating with '/signalr/negotiate?    clientProtocol=1.5&connectionData=%5B%5D'.
[17:56:53 GMT-0500 (Eastern Standard Time)]     SignalR: webSockets transport starting.
[17:56:53 GMT-0500 (Eastern Standard Time)]     SignalR: Connecting to websocket endpoint     'ws://samiweb.azurewebsites.net/signalr/connect?    transport=webSockets&clientProtocol=1.5&connectionToken=yKn2ns1bOenZLiUtCiOSSfQg    YCl%2FyVAvxKejSZx2x0svkyzIJJ85qjNMk7IBjy8Nes0Lg9W%2BUTAPW21z6rVHTwXbb4wxaZhVwn1J    vzrNra0WhYCuXMiu6kLYs0FWuRUy&connectionData=%5B%5D&tid=1'.
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: Websocket opened.
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: webSockets transport connected. Initiating start request.
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: The start request succeeded. Transitioning to the connected state.
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332,     keep alive timeout of 20000 and disconnecting timeout of 30000
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: Invoking saminotificationhub.GetNotifications
[17:56:54 GMT-0500 (Eastern Standard Time)]     SignalR: Invoked saminotificationhub.GetNotifications

任何帮助将不胜感激!

最佳答案

来自您的 SignalR 客户端日志:

No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to.

据我所知,正常的客户端日志如下所示:客户端订阅了集线器“notificationhub”。您可以尝试在 $.connection.hub.start() 之前声明您的客户端方法。

关于c# - Signalr 未在 Azure 主机上发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274367/

相关文章:

基于 Azure Blob 存储角色的访问控制

signalr - 是否可以从 Postman 调用 SignalR Hub

c# - 由于其保护级别而无法访问结构

c# - 可以将 C# 枚举声明为 bool 类型吗?

c# - 如何创建 public String Replace with 4 种方法

azure - 连接到 Azure AD 条件访问 VPN 命令行

Azure kubernetes 服务负载均衡器外部 IP 无法访问

javascript - 何时从浏览器关闭与 SignalR 的连接

signalr - Azure SignalR 服务 : No active connection for user

c# - 处理多个断言并在未找到时失败测试