简体   繁体   English

部署站点时SignalR消息不起作用

[英]SignalR messages not working when site is deployed

I am building a web site using ASP.NET Core 2.2, and SignalR. 我正在使用ASP.NET Core 2.2和SignalR构建网站。

The prime use of SignalR is to send out notifications when donations are submitted. SignalR的主要用途是在提交捐赠时发出通知。 I have a scheduled job running Quartz.net that sends out a notification with the latest donations. 我有一个运行Quartz.net的计划作业,该作业发送带有最新捐赠的通知。

In the scheduled job, I inject an instance of IServiceScopeFactory and use it to create an IHubContext<CampaignHub> as follows (irrelevant code omitted for clarity)... 在计划的作业中,我注入了IServiceScopeFactory的实例,并使用它来创建IHubContext<CampaignHub> ,如下所示(为清楚起见,省略了相关代码)...

public class DonationsNotifierJob : IJob {
  private readonly IServiceScopeFactory _scopeFactory;

  public DonationsNotifierJob(IServiceScopeFactory scopeFactory) =>
    _scopeFactory = scopeFactory;

  public async Task Execute(IJobExecutionContext context) {
    using (IServiceScope scope = _scopeFactory.CreateScope()) {
      IHubContext<CampaignHub> hubContext = scope.ServiceProvider
        .GetRequiredService<IHubContext<CampaignHub>>();
      await hubContext.Clients.All
        .SendAsync("UpdatedCampaignData", new LiveCampaignData {
          // Data loaded here...
        });
    }
  }
}

The Razor for one of the pages that is supposed to pick up the notifications includes the following JavaScript... 应当接收通知的页面之一的Razor包含以下JavaScript ...

  var connection = new signalR.HubConnectionBuilder()
    .withUrl("/campaignHub")
    .build();
  connection.start();

  connection.on("UpdatedCampaignData", function(d) {
    // Code omitted for clarity
  });

This works fine when I'm running in Visual Studio (2017 Enterprise), but when I deploy the site to a test server, the page that contains the JavaScript above never receives notifications. 当我在Visual Studio(2017 Enterprise)中运行时,这可以很好地工作,但是当我将网站部署到测试服务器时,包含上述JavaScript的页面将永远不会收到通知。

I tried adding the usual "chat room" code you see in the samples, and that worked fine, so SignalR is working to some degree. 我尝试添加示例中看到的常规“聊天室”代码,并且效果很好,所以SignalR在某种程度上可以正常工作。 Not only that, but one of the pages that sends out a SignalR notification directly (using the same hub method as shown above) works fine, so it seems to be a problem only in the scheduled job. 不仅如此,而且直接发送SignalR通知的页面之一(使用与上述所示相同的集线器方法)也可以正常工作,因此似乎仅在计划的作业中才是问题。

Injection is working fine, as I don't get any null reference exceptions. 注入工作正常,因为我没有任何空引用异常。

I really have no idea how to start debugging this. 我真的不知道如何开始调试它。 It's the same code running in both cases, and I can see from the logging that the line in the scheduled job where the notification is sent is called, but I have no idea what happens to it then. 两种情况下运行的都是相同的代码,从日志记录中我可以看到已调度通知发送通知的作业中的行被调用,但是我不知道接下来会发生什么。 I haven't found any way to tell if the notification isn't being sent, or if it is being sent but the target page doesn't pick it up. 我还没有找到任何方法来告知是否未发送通知,或者是否正在发送通知,但目标页面没有接收到通知。

Anyone able to give me any idea how I find out what's going wrong? 任何人都可以告诉我如何找出问题所在吗? Sorry if there isn't enough info here, but I don't know what else to tell you. 很抱歉,如果这里没有足够的信息,但是我不知道还能告诉您什么。

Thanks 谢谢

I think you are missing the invoke method. 我认为您缺少invoke方法。 Below is my example 下面是我的例子

(function () {
        var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();

        connection.start().then(function () {
            console.log("connected");

            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    sessionStorage.setItem('conectionId', connectionId);
                    // Send the connectionId to controller
                }).catch(err => console.error(err.toString()));;


        });

        $("#sendmessage").click(function () {
            var connectionId = sessionStorage.getItem('conectionId');
            connection.invoke("Send", connectionId);
        });

        connection.on("ReceiveMessage", function (message) {
            console.log(message);
        });

    })();

And the hub code 和中心代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace SignalR.Models
{
    public class ConnectionHub : Hub
    {
        public async Task Send(string userId)
        {
            var message = $"Send message to you with user id {userId}";
            await Clients.Client(userId).SendAsync("ReceiveMessage", message);
        }

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }
    }
}

You can read more here 你可以在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM