locked
Webapi call from not signalr client in Web Application with Signalr and Webapi RRS feed

  • Question

  • User-2715168 posted

    I have created a MVC5 Web Application with Webapi included.  It also has signalr.  My problem is when I call an api controller from a non signalr client the code executes to get the hub context but does not fire on the clients.  If I call the same webapi endpoint from a signalr client then signalr calls the clients properly.  I have a windows service that updates database but does not need to be a signalr client.  So it calls a webapi endpoint.  I want this to notify signalr clients in the same webapplication.  Can this be done or is there a better way?

    Thursday, November 7, 2019 6:25 PM

All replies

  • User61956409 posted

    Hi glfcstman,

    I want this to notify signalr clients in the same webapplication.  Can this be done or is there a better way?

    If you'd like to push updates/data to web application clients by calling hub method from your Web API action, the approach you mentioned should be able to help achieve the requirement.

    My problem is when I call an api controller from a non signalr client the code executes to get the hub context but does not fire on the clients.  If I call the same webapi endpoint from a signalr client then signalr calls the clients properly.

    To reproduce the scenario you mentioned, I create a simple sample like below, which work well on my side, you can refer to it.

    Hub class

    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }

    MVC client

    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    
    @section scripts{
        <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
        <script src="~/signalr/hubs"></script>
    
        <script>
            $(function () {
                // Reference the auto-generated proxy for the hub.
                var chat = $.connection.chatHub;
                // Create a function that the hub can call back to display messages.
                chat.client.addNewMessageToPage = function (name, message) {
                    // Add the message to the page.
                    $('#discussion').append('<li><strong>' + htmlEncode(name)
                        + '</strong>: ' + htmlEncode(message) + '</li>');
                };
                // Get the user name and store it to prepend to messages.
                $('#displayname').val(prompt('Enter your name:', ''));
                // Set initial focus to message input box.
                $('#message').focus();
                // Start the connection.
                $.connection.hub.start().done(function () {
                    $('#sendmessage').click(function () {
                        // Call the Send method on the hub.
                        chat.server.send($('#displayname').val(), $('#message').val());
                        // Clear text box and reset focus for next comment.
                        $('#message').val('').focus();
                    });
                });
            });
            // This optional function html-encodes messages for display in the page.
            function htmlEncode(value) {
                var encodedValue = $('<div />').text(value).html();
                return encodedValue;
            }
        </script>
    }

    Web API

    [Route("api/GetUpdates")]
    public IEnumerable<string> Get()
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        hubContext.Clients.All.addNewMessageToPage("API", "test data from API");
    
        return new string[] { "value1", "value2" };
    }

    Console client (in your scenario, it would be a windows service application)

    HttpClient httpClient = new HttpClient();
    HttpResponseMessage res = httpClient.GetAsync("http://localhost:51613/api/getupdates").Result;
    
    if (res.StatusCode== HttpStatusCode.OK)
    {
        Console.WriteLine("Updates have been pushed to clients.");
    }
    else
    {
        Console.WriteLine("Pushing updates failed.");
    }

    Test Result

    With Regards,

    Fei Han

    Friday, November 8, 2019 2:58 AM