40 lines
1.0 KiB
C#
40 lines
1.0 KiB
C#
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace LiveChat.Server.Hubs;
|
|
|
|
public class ChatHub : Hub
|
|
{
|
|
private readonly ChattingContext _context;
|
|
public override async Task OnConnectedAsync()
|
|
{
|
|
using (var db = new ChattingContext())
|
|
{
|
|
var messages = db.Messages.ToList();
|
|
|
|
messages.ForEach(Console.WriteLine);
|
|
|
|
// Send the messages to the caller
|
|
await Clients.Caller.SendAsync("ReceiveMessages", messages);
|
|
}
|
|
}
|
|
|
|
public async Task SendMessage(string user, string message)
|
|
{
|
|
using (var db = new ChattingContext())
|
|
{
|
|
var messageData = new ChatMessage
|
|
{
|
|
User = user,
|
|
Message = message,
|
|
};
|
|
Console.WriteLine(messageData);
|
|
var dbSave = db.Messages.Add(messageData);
|
|
Console.WriteLine(dbSave);
|
|
await Clients.All.SendAsync("ReceiveMessage", user, message);
|
|
db.SaveChanges();
|
|
}
|
|
}
|
|
}
|
|
|