I have an asp.net mvc 4 app that uses SignalR.
When an user is connected I want to notify everyone of that (sending to "all" for the moment just to test it). In my Hub clas I have this:
public override System.Threading.Tasks.Task OnConnected()
{
NotifyAllOfUserLogin();
return base.OnConnected();
}
In the _layout.cshtml, I have this:
<script type="text/javascript">
$(document).ready(function () {
var proxy = $.connection.messagehub;
proxy.client.messageAll = function (message) {
$('#messages').prepend('<p style=\'white-space:pre;\'>' + message + '</p><br />');
};
$("#btnSubmitMessage").click(function () {
proxy.server.messageAll($("#txtMessage").val());
$("#txtMessage").val('');
});
$.connection.hub.start();
});
</script>
While this works, I think writing this in the masterpage is a mistake, since the hub connection will be reinitialized for every page that inherits the master, so OnConnected will be called a lot of times.
How should I deal with this properly, calling OnConnect only when the user logs into the application, and onDisconnected when the user logs out?