在ASP.NET Core SignalR中,如何从服务器向客户端发送消息? [英] In ASP.NET Core SignalR, how do I send a message from the server to a client?

查看:1125
本文介绍了在ASP.NET Core SignalR中,如何从服务器向客户端发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用新发布的ASP.NET Core 2.1成功设置了SignalR服务器和客户端.我通过将ChatHub扩展为Hub来建立了一个聊天室:每当有邮件从客户端传入时,服务器就会通过Clients.Others将其炸回.

I've successfully setup a SignalR server and client using the newly released ASP.NET Core 2.1. I built a chat room by making my ChatHub extend Hub: whenever a message comes in from a client, the server blasts it back out via Clients.Others.

我还不了解如何将消息发送给客户端,而不是作为对传入消息的响应.如果服务器正在工作并产生结果,我如何获得对Hub的访问权限以便向特定客户端发送消息? (或者我什至需要访问Hub?还有另一种发送消息的方式吗?)

What I do not yet understand is how to send a message to clients not as a response to an incoming message. If the server is doing work and produces a result, how do I gain access to the Hub in order to message particular clients? (Or do I even need access to the Hub? Is there another way to send messages?)

搜索此问题很困难,因为大多数结果来自旧版本的ASP.NET和SignalR.

Searching this issue is difficult as most results come from old versions of ASP.NET and SignalR.

推荐答案

您可以将IHubContext<T>类注入服务并使用该服务调用客户端.

You can inject the IHubContext<T> class into a service and call the clients using that.

public class NotifyService
{
    private readonly IHubContext<ChatHub> _hub;

    public NotifyService(IHubContext<ChatHub> hub)
    {
        _hub = hub;
    }

    public Task SendNotificationAsync(string message)
    {
        return _hub.Clients.All.InvokeAsync("ReceiveMessage", message);
    }
}

现在,您可以将NotifyService注入到您的班级中,并将消息发送给所有客户端:

Now you can inject the NotifyService into your class and send messages to all clients:

public class SomeClass
{
    private readonly NotifyService _service;

    public SomeClass(NotifyService service)
    {
        _service = service;
    }

    public Task Send(string message)
    {
        return _service.SendNotificationAsync(message);
    }
}

这篇关于在ASP.NET Core SignalR中,如何从服务器向客户端发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆