I am creating a chat between 2 users. Here's my hub and hub client:
public class ConversationHub : Hub<IConversationHubClient>
{
public override Task OnConnected()
{
var id = this.Context.User.Identity.GetUserId();
//when I breakpoint here, I can see the id of my connected user.
return base.OnConnected();
}
}
public interface IConversationHubClient
{
void MessageReceived(string conversationId,
string userId,
string text,
DateTime date,
bool isUser);
}
And from the mvc controller, I am calling:
string userId = this.User.Identity.GetUserId();
_conversationHub.Clients
.User(userId)
.MessageReceived(model.ConversationId, userId , model.Text, model.Date, true);
//I want to send back the message to the user, for testing purposes
And finally here is the front-end:
var conversationhub = $.connection.conversationHub;
//messageReceived
conversationhub.client.MessageReceived = function (conversationId, userId, text, sentOn, isUser){
alert(':D');
};
I am expecting to see the alert when I trigger my mvc controller method but nothing happens. It seems to me that the user is not registered in the connected users but I don't understand why and how to register it. Can someone help me on that?
Well, turns out it didn't work because of the way I was injecting the hubContext on my MVC Controller.
I followed the article on SignalR DI with ninject.
My binding was wrong. After following the example, I change my binding to:
this.Kernel.Bind<IHubContext<IConversationHubClient>>()
.ToMethod(x => GlobalHost.DependencyResolver.Resolve<IConnectionManager>()
.GetHubContext<ConversationHub, IConversationHubClient>());
And everything worked!