[英]SignalR messages not working when site is deployed
我正在使用ASP.NET Core 2.2和SignalR构建网站。
SignalR的主要用途是在提交捐赠时发出通知。 我有一个运行Quartz.net的计划作业,该作业发送带有最新捐赠的通知。
在计划的作业中,我注入了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...
});
}
}
}
应当接收通知的页面之一的Razor包含以下JavaScript ...
var connection = new signalR.HubConnectionBuilder()
.withUrl("/campaignHub")
.build();
connection.start();
connection.on("UpdatedCampaignData", function(d) {
// Code omitted for clarity
});
当我在Visual Studio(2017 Enterprise)中运行时,这可以很好地工作,但是当我将网站部署到测试服务器时,包含上述JavaScript的页面将永远不会收到通知。
我尝试添加示例中看到的常规“聊天室”代码,并且效果很好,所以SignalR在某种程度上可以正常工作。 不仅如此,而且直接发送SignalR通知的页面之一(使用与上述所示相同的集线器方法)也可以正常工作,因此似乎仅在计划的作业中才是问题。
注入工作正常,因为我没有任何空引用异常。
我真的不知道如何开始调试它。 两种情况下运行的都是相同的代码,从日志记录中我可以看到已调度通知发送通知的作业中的行被调用,但是我不知道接下来会发生什么。 我还没有找到任何方法来告知是否未发送通知,或者是否正在发送通知,但目标页面没有接收到通知。
任何人都可以告诉我如何找出问题所在吗? 很抱歉,如果这里没有足够的信息,但是我不知道还能告诉您什么。
谢谢
我认为您缺少invoke方法。 下面是我的例子
(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);
});
})();
和中心代码
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;
}
}
}
你可以在这里阅读更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.