SignalR - How can I call the Hub method on the server from the server

I have SignalR running between an ASP.NET server (formerly MVC) and a Windows service client in the sense that the client can call methods on a hub server and then display them in browsers. Hub Code:

  public class AlphaHub : Hub
        {
            public void Hello(string message)
            {
                // We got the string from the Windows Service 
                // using SignalR. Now need to send to the clients
                Clients.All.addNewMessageToPage(message);

                // Call Windows Service
                string message1 = System.Environment.MachineName;
                Clients.All.Notify(message1);


            }
     public void CallForReport(string reportName)
     {
          Clients.All.CallForReport(reportName);
     }

On the client (Windows service), I called methods on the hub:

var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/signalr",
                    useDefaultUrl: false);
                IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");

                await hubConnection.Start();
                string cid = hubConnection.ConnectionId.ToString();
                eventLog1.WriteEntry("ConnectionID: " + cid);
                // Invoke method on hub

                await alphaProxy.Invoke("Hello", "Message from Service - ConnectionID: " + cid + " - " + System.Environment.MachineName.ToString() + " " + DateTime.Now.ToString());

Now suppose this scenario: the user will use a specific form of ASP.NET, such as Insured.aspx on the server. In this, I want to call CallForReport, and then call this method on the client:

 public void CallFromReport(string reportName)
        {
            eventLog1.WriteEntry(reportName);
        }

How can I get a connection to my own hub on the server and call the method. I tried the following things from Insured.aspx:

 protected void Page_Load(object sender, EventArgs e)
        {
            // Hubs.AlphaHub.CallForReport("Insured Report");
            // IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlphaHub>();
            // hubContext.Clients.All.CallForReport("Insured Report");
        }
+4
source share
1

IHubProxy.On. , CallFromReport AlphaHub IHubProxy .

 var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/");
 IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");

 alphaProxy.On<string>("CallForReport", CallFromReport);

 await hubConnection.Start();

 // ...

, , Page_Load, .

protected void Page_Load(object sender, EventArgs e)
{
    IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlphaHub>();
    hubContext.Clients.All.CallForReport("Insured Report");
}
+8

Source: https://habr.com/ru/post/1527017/


All Articles