Arayn
Arayn

Reputation: 1106

Issue whille calling SignalR hub from WebAPI controller

I cannot figure out what is going wrong out here.

I have created new project from the ASP.NET MVC WebAPI template.Added a new SignalR Hub to the project called MyHub. Added an HTML page that on load, connects to Hub and sends a message. HTML page has a button that when clicked will fire an ajax call to the APIController's post method. In the APIController's post method, I want to broadcast a message to all the connected clients. I cannot get this to work.

ChatHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRServerAPIHub
{
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}

Index.html

<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <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>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (message) {
            // Html encode display message.
                var encodedMsg = $('<div />').text(message).html();
            // Add the message to the page.
            $('#discussion').append('<li><strong>' + </strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
        };
        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start()//.done(function () {
            $('#sendmessage').click(function () {
                $.ajax({
                    url: "api/Test/PostSampleMessage",
                    data: { 'Message': $('#message').val() },
                    type: "POST"
                });
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        //});
    });
</script>
</body>
</html>

Whenever the connected hub receives a new message, a new item is added to the unordered list. There is a button that makes an Ajax call into the TestController post method.

API Controller

public class TestController : ApiController
{
    [HttpPost]
    public void PostSampleMessage([FromBody] FormData data)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        hubContext.Clients.All.send(data.Message);
    }
}

FormData Class

public class FormData
    {
        public string Message { get; set; }
    }

Startup.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;

[assembly: OwinStartup(typeof(SignalRServerAPIHub.Startup))]

namespace SignalRServerAPIHub
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration { };
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

Looks like the Hub call is not working. I am not getting any error generated from this, but not getting the message back for the clients.

Any help is appreciated.

Upvotes: 2

Views: 5761

Answers (1)

Quentin Roger
Quentin Roger

Reputation: 6538

You should add something like this in the js :

chat.client.send= function (message) {
        alert(message)
};

or change the server call to (cause in your code you are trying to call the send method on the client):

[HttpPost]
public void PostSampleMessage([FromBody] FormData data)
{
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    hubContext.Clients.All.broadcastMessage(data.Message);
}

Upvotes: 3

Related Questions