Im trying to establish a coss-domain connection. In my JavaScript client I see no problem with the connection, but if I send a signal from the hub, the javascript method is not getting hit. In console there is no error displayed. The JavaScript variable "chat" is defined. I looked at sever tutorials in the internet and I mostly copied the code but it doesn't work.
Console Application host:
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:43253/";
using (WebApp.Start(url))
{
Console.WriteLine($"Server running on {url}");
Console.ReadKey();
MyHub hub = new MyHub();
hub.Send("test", "test");
Console.ReadKey();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
// Setup the cors middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch is already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
}
public class MyHub : Hub
{
public override Task OnConnected()
{
Console.WriteLine("connected");
return base.OnConnected();
}
public void Send(string name, string message)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.addMessage(name, message);
}
}
JavaScript client:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="image">
</div>
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="http://localhost:43253/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://localhost:43253/signalr";
var chat = $.connection.myHub;
chat.client.addMessage = function (name, message) {
console.log(name + message);
}
});
</script>
</body>
</html>
I fixed it. The problem was i forgot to start the connection. Just added: $.connection.hub.start(); at the end of the JavaScript client