locked
How to call a SignalR Hub in a Web Api from a MVC Controller class? RRS feed

  • Question

  • User-2145124708 posted

    I am completely new to SignalR. I have a ASP.Net net MVC web application (not .Net Core). But the business logic is written in a separate Web Api hosted in a different server. Now I want to call a SignalR Hub residing in above mentioned Web Api server from my client's Controller class. The reason why I am not directly calling WebApi server from javascript is I want to pass the currently logged UserID to the Hub too. So I believe it is more secure to get the current logged UserID from the Session variable I created in MVC controller class (at client's side). Could someone help me with the solution? It will be really helpful if you can show me the complete code. Because I am new to the SignalR thing. 

    Sunday, April 12, 2020 7:50 PM

All replies

  • User283571144 posted

    Hi chamila91,

    As far as I know,if you want to access the server hub in MVC controller, I suggest you could try to use signalr client library

    Then you could use below codes to call the server hub method.

    Server code for a method that has no return value

    public class StockTickerHub : Hub
    {
        public void JoinGroup(string groupName)
        {
            Groups.Add(Context.ConnectionId, groupName); 
        }
    }

    Client hub method:

    using (var hubConnection = new HubConnection("http://www.contoso.com/")) 
    {
        IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
        stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
        await hubConnection.Start();
        stockTickerHubProxy.Invoke("JoinGroup", "SignalRChatRoom");
    }
    

    Best Regards,

    Brando

    Monday, April 13, 2020 2:06 AM
  • User-2145124708 posted

    Hi Brando. Thanks for the reply. Can you also tell me what are these names in your example code above? 

    UpdateStockPrice
    SignalRChatRoom

    And please explain below code part: 

    stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
    Wednesday, April 15, 2020 5:55 PM
  • User283571144 posted

    Hi chamila91,

    This code is used to log some part of message when connected to the Signlar hub. The stock is my custom model.

    You could replace it with below codes:

                hubProxy.On<string>("displayMessage", (data) => hubConnection.TraceWriter.WriteLine(data));
    

    Best Regards,

    Brando

    Monday, April 20, 2020 1:47 AM