How is SignalR aware of userID while EF Core Identity has been deployed as login system?
-
I'm using EF Core Identity as register/login system in my project. I tried to use signalR to push notification when a new message is send to a user. I have a form with two inputs, one for user who will receive the message and the other for the main message text. The message information is stored in the database and a notification is send to the client. I used the following codes: Adding signalR service to **program.cs**:
builder.Services.AddSignalR();
.
.
app.MapHub("/msgHub");Code for **Hub**:
public class MessageHub : Hub
{
private readonly IUserRepository _userRepository;
private readonly ICostCenterRepository _costcenterRepository;public MessageHub(IUserRepository userRepository, ICostCenterRepository costcenterRepository) { \_userRepository = userRepository; \_costcenterRepository = costcenterRepository; } public async Task SendMessage(string costCenter) { string userId = \_userRepository.GetUserIdByCostCenter(costCenter).ToString(); await Clients.User(userId).SendAsync("ReceiveMessage"); } }
Code for **message.js**:
var connection = new signalR.HubConnectionBuilder().withUrl("/msgHub").withAutomaticReconnect().build();
connection.start();
document.getElementById("sendBtn").addEventListener("click", function () {
var costCenter = $("#cost-center").val();
connection.invoke("SendMessage", costCenter).catch(function (err) {
return console.error(err.tostring());
});
});Script in the view:
connection.on("ReceiveMessage", function () { location.reload(); }); connection.start().catch(function (err) { return console.error(err.tostring()); });
Controller for sending message:
public JsonResult Send(string inputMessageText, string costCenter)
{
int CurrentUserId = Convert.ToInt32(HttpContext.Session.GetString("userId"));
int receiverId = _userRepository.GetUserIdByCostCenter(costCenter);if (!ModelState.IsValid) { return Json(new { success = false}); } else { var newMessage = new Message()