user2471435
user2471435

Reputation: 1674

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

I have SignalR working between an ASP.NET (formerly MVC) server and a Windows Service client in the sense that the client can call methods on the Server Hub and then display to Browsers. The Hub code is:

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 have been calling 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 go to a particular ASP.NET form like Insured.aspx on the server. In that I want to call CallForReport and then call this method on the client:

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

How do I get a connection to my own Hub on the server and call the method? I tried the following 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");
}

Upvotes: 6

Views: 11903

Answers (1)

halter73
halter73

Reputation: 15234

I don't see any calls to IHubProxy.On. That is the method you need to hook up your CallFromReport method to your AlphaHub IHubProxy on the client.

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

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

 await hubConnection.Start();

 // ...

Once you have that, the last two lines you have commented in Page_Load should work.

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

Upvotes: 8

Related Questions