LiveChat/Hubs/ChatHub.cs

40 lines
1.0 KiB
C#
Raw Normal View History

2023-03-27 13:30:27 +00:00
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();
}
}
}