0

I have an ASP.NET Web API that exposes some REST methods. The client browser authenticates with the API using a Login screen. I would like to broadcast a message (javascript alert) to all clients when another client authenticates with the API. No need for the client to invoke a method on the server, just the server calling a single method on the client to display a Javascript Alert.

My Hub class:

public class MyHub : Hub
{
  public void BroadcastMessage(string userName)
  {
    Clients.All.notify(userName);
  }
}

Inside my CustomOAuthProvider classs where user authentication takes place:

if (userAuthenticated)
{
    var signalRContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    signalRContext.Clients.All.notify(context.UserName);
}

Here is my index.html file with the relevant scripts:

<script src="scripts/jquery-2.2.2.min.js"></script>
<script src="scripts/jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:49834/signalr/hubs"></script>
<script>
(function ($) {
    $(function () {
        var hubProxy = $.connection.myHub;
        hubProxy.client.notify = function (username) {
            alert(username + ' has logged in');
        };
        $.connection.hub.start();
    });
})(jQuery);
</script>

Note that the path to the dynamically generated SignalR Hubs script has localhost:49834. This is the url to my web api. I included this because the client is running in a Node.js http-server and is not part of the ASP.NET Web Api project.

When I run this I get no errors on the console and no alerts. I login with one user then open a separate browser and login with a second user. I am not sure why I am not getting a Javascript Alert with the authenticated username.

webworm
  • 10,587
  • 33
  • 120
  • 217
  • Just to be sure, if you put a breakpoint at `signalRContext.Clients.All.notify(context.UserName);` it is successfully hit, right? – Federico Dipuma Apr 12 '16 at 16:37
  • @FedericoDipuma - Yes indeed. The breakpoint is hit. I am finding the following Javascript error in the client. `Failed to load resource: the server responded with a status of 404 (Not Found)`. It references this URL `http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22loginhub%22%7D%5D&_=1460479116096` – webworm Apr 12 '16 at 16:42
  • I am thinking that because the client and API are hosted at different URLs the path to the `signalr/hubs` auto-generated script is not being found at `localhost:8080` but instead should reference the API server `localhost:49834` which is the URL of the API server. – webworm Apr 12 '16 at 17:02
  • Yes, I also believe that it could be related to an issue with SignalR proxies with hard coded paths. Could this answer be useful? http://stackoverflow.com/a/16875998/3670737 – Federico Dipuma Apr 12 '16 at 17:08

0 Answers0