Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

huangapple go评论56阅读模式
英文:

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

问题

I am working with ASP.NET Boilerplate project for .NET Core and Angular. In my .NET Core project, I have a background worker. My goal is to send notification to the user in every 2 milliseconds. I have created a Notification Hub with SignalR.

Here is the hub code:

public class MyTestHub : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }
    public ILogger Logger { get; set; }

    public MyTestHub()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("getMessage", string.Format("User {0}: {1}", AbpSession.UserId, message));
    }

    public override async Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
        Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId);
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        await base.OnDisconnectedAsync(exception);
        Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId);
    }
}

I have registered the Hub in the startup file.

And here is my background worker code, which is sending a notification to all users every 2 milliseconds:

public class SendingMessageWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
{
    private readonly IHubContext<MyTestHub> _notificationHubContext;

    public SendingMessageWorker(AbpTimer timer, IHubContext<MyTestHub> notificationHubContext) : base(timer)
    {
        Timer.Period = 2000;
        _notificationHubContext = notificationHubContext;
    }

    [UnitOfWork]
    protected override void DoWork()
    {
        using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
        {
            string message = "Hi! This is a sample message " + Clock.Now;
            AsyncHelper.RunSync(() => _notificationHubContext.Clients.All.SendAsync("App.SimpleMessage", message));
        }
    }
}

I tested the background worker with the Hub in the Chrome inspection network tab and can see that the hub is sending the message constantly.

Now, with the help of this link from ASP.NET Boilerplate website, I have added the following code in my Angular project. In the app.component.ts file, in the ngOnInit function, I have added this code:

ngOnInit(): void {
    SignalRAspNetCoreHelper.initSignalR(() => {
        var chatHub = null;

        abp.signalr.startConnection(abp.appPath + 'signalr-myTestHub', function (connection) {
            chatHub = connection; // Save a reference to the hub
            connection.on('getMessage', function (message) { // Register for incoming messages
                console.log('Received the message: ' + message);
            });
        }).then(function (connection) {
            abp.log.debug('Connected to myTestHub server!');
            abp.event.trigger('myTestHub.connected');
        });

        abp.event.on('myTestHub.connected', function (notification) { // Register for connect event
            console.log("Log: ", notification);
            alert(notification);
            chatHub.invoke('sendMessage', "Hi everybody, I'm connected to the chat!"); // Send a message to the server
        });
    });
}

Now, each time the background worker sends the push notification, in the frontend application, I should see an Alert Message and a Log in the Browser. Because I have the below code in Angular:

abp.event.on('myTestHub.connected', function (notification) { 
    console.log("Log: ", notification);
    alert(notification);
    chatHub.invoke('sendMessage', "Hi everybody, I'm connected to the chat!"); 
});

But I don't see any alert message or log in the console tab of the browser. Only once when I refresh the page an alert appears with an undefined value. This alert only shows at the first time when the page loads. But I am expecting the alert message every 2 seconds without the page refresh.

英文:

I am working with ASP.NET Boilerplate project for .NET Core and Angular. In my .NET Core project, I have a background worker. My goal is to send notification to the user in every 2 milliseconds. I have created a Notification Hub with SignalR.

Here is the hub code:

public class MyTestHub : Hub, ITransientDependency
{
	public IAbpSession AbpSession { get; set; }
	public ILogger Logger { get; set; }

	public MyTestHub()
	{
		AbpSession = NullAbpSession.Instance;
		Logger = NullLogger.Instance;
	}

	public async Task SendMessage(string message)
	{
		await Clients.All.SendAsync(&quot;getMessage&quot;, string.Format(&quot;User {0}: {1}&quot;, AbpSession.UserId, message));
	}

	public override async Task OnConnectedAsync()
	{
		await base.OnConnectedAsync();
		Logger.Debug(&quot;A client connected to MyChatHub: &quot; + Context.ConnectionId);
	}

	public override async Task OnDisconnectedAsync(Exception exception)
	{
		await base.OnDisconnectedAsync(exception);
		Logger.Debug(&quot;A client disconnected from MyChatHub: &quot; + Context.ConnectionId);
	}
}

I have registered the Hub in the startup file:

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

And here is my background worker code, which is sending a notification to all user in every 2 milliseconds:

public class SendingMessageWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
{	
	private readonly IHubContext&lt;MyTestHub&gt; _notificationHubContext;
	
	public SendingMessageWorker(AbpTimer timer,
		IHubContext&lt;MyTestHub&gt; notificationHubContext) : base(timer)
	{
		Timer.Period = 2000;		
		_notificationHubContext = notificationHubContext;
	}

	[UnitOfWork]
	protected override void DoWork()
	{
		using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
		{			
			string message = &quot;Hi! This is a sample message &quot; + Clock.Now;
			AsyncHelper.RunSync(() =&gt; _notificationHubContext.Clients.All.SendAsync(&quot;App.SimpleMessage&quot;, message));
		}
	}
}

I tested the background worker with Hub in the chrome inspection network tab and can see that the hub sending the message constantly.

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

Now with the help of this link from ASP.NET Boilerplate website, I have added the below code in my Angular project. In the app.component.ts file, in ngOnInit function I have added this code:

ngOnInit(): void {
	
	SignalRAspNetCoreHelper.initSignalR(() =&gt; {
		var chatHub = null;

		abp.signalr.startConnection(abp.appPath + &#39;signalr-myTestHub&#39;, function (connection) {
			chatHub = connection; // Save a reference to the hub
			connection.on(&#39;getMessage&#39;, function (message) { // Register for incoming messages
				console.log(&#39;Received the message: &#39; + message);
			});
		}).then(function (connection) {
			abp.log.debug(&#39;Connected to myTestHub server!&#39;);
			abp.event.trigger(&#39;myTestHub.connected&#39;);
		});

		abp.event.on(&#39;myTestHub.connected&#39;, function (notification) { // Register for connect event
			console.log(&quot;Log: &quot;, notification);
			alert(notification)
			chatHub.invoke(&#39;sendMessage&#39;, &quot;Hi everybody, I&#39;m connected to the chat!&quot;); // Send a message to the server
		});
	});		
}

Now each time the background worker sends the push notification, in the frontend application I should see an Alert Message and a Log in the Browser. Because I have the below code in Angular:

abp.event.on(&#39;myTestHub.connected&#39;, function (notification) { 
    console.log(&quot;Log: &quot;, notification);
    alert(notification)
    chatHub.invoke(&#39;sendMessage&#39;, &quot;Hi everybody, I&#39;m connected to the chat!&quot;); 
});

But I don't see any alert message or log in the console tab of the browser. Only once when I refresh the page an alert appears with undefined value. This alert only shows at the first time when the page Loads. But I am expecting the alert message in every 2 seconds without the page refresh.

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

Can anyone help me to understand where is the problem and how to solve this. I am very new to aspnetboilerplate and SignalR.

答案1

得分: 1

当客户端创建连接并连接到Hub时,我们使用 abp.event.trigger('myTestHub.connected'); 来调用已注册的事件 myTestHub.connected

我们可以看到在 abp.event.trigger('myTestHub.connected'); 中没有参数,这就是为什么 notification 是未定义的。

我的测试结果。

英文:

When the client create the connection and connected the hub, we are using abp.event.trigger(&#39;myTestHub.connected&#39;); to call the registered event myTestHub.connected.

We can see there is no params in abp.event.trigger(&#39;myTestHub.connected&#39;);, that why the notification is undefined.

My test result.

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

Problem in receiving SignalR notification in Angular project sent from background worker in .NET Core with aspnetboilerplate

huangapple
  • 本文由 发表于 2023年7月12日 23:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定