Reputation: 17
My SignalR ChatHub requires Authorization in order to send a message to another user. If a users sends a message, but if the recipient is not connected to the Hub, then it will be saved in the database. Now that part works fine, I am able to save messages to the recipients Inbox.
IdentityModel :
public class ApplicationUser : IdentityUser
{
public virtual ICollection<MyMessage> Inbox { get; set; }
//......
}
This is how messages are saved if not connected to Hub:
var recipient = UserManager.FindById(id);
if (recipient != null)
{
if (recipient.Message_Inbox == null)
{
recipient.Message_Inbox = new List<MyMessage>();
}
recipient.Inbox.Add(new MyMessage() { Id = Guid.NewGuid().ToString(), SentBy = userId, Message = message});
UserManager.Update(recipient);
}
And then OnConnected, the database is queried and the user is sent a list of messages. But that doesn't work. If I create a sample list of messages and send it, my client receives it but not if I send it from the server.
List<MyMessage> inbox = user.Inbox.ToList();
Clients.Client(Context.ConnectionId).sendInbox(inbox); //doesn't work
//but if I do this
List<MyMessage> list = new List<MyMessage>()
{
new MyMessage() { SentBy = "asdsadd", Message = "First", Id = "sds" },
new MyMessage() { SentBy = "asdsadd1", Message = "Second", Id = "sds2" },
};
Clients.Client(Context.ConnectionId).sendInbox(list); // IT WORKS
This is how I get my UserManager :
private ApplicationUserManager _userManager;//updated
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Context.Request.GetHttpContext().GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
Upvotes: 0
Views: 575
Reputation: 17
Solved the problem by using Json to serialize it.
string jsonObject = JsonConvert.SerializeObject(inbox);
Not sure why my test list didn't need to be serialized, but oh well. It works.
Upvotes: 0