We're developing a instructional site that uses SignalR for communication.
The instructor signs in and sets up the instructional material and when ready, will publish a workshop ID so users can input this value into a box along with a user name and join the conference.
There is no need for the participants to "officially log in" as they are just viewing the conference.
However, for signal R groups and communication I have got to get the workshop ID and a username into the Hub.
How can I do this without making the user create login credentials? I just need to send some parameters (workshopID and Username) to the hub when the SignalR code creates a connection. Because the instructors have to log in, I don't want to mess with the default behaviors.
I'm using MVC core 2.0.
The following Code works, but I send/receive messages to everyone in the system, not just the targeted group:
Java script:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/Workshop")
.build();
//
connection.on("ReceiveMessage", (user, userID, message) => {
const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const encodedMsg = user + " says " + msg;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
//connection.hub.qs = "Name=John";
connection.start().catch(err => console.error(err.toString()));
Csharp:
public override async Task OnConnectedAsync()
{
var test = Context.User.Identity.Name; //Only works if user is signed in
// var test2 = Context.User.FindFirst("WebID").Value;
await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
await base.OnConnectedAsync();
}
I've tried adding a claim (var test2...) and retrieving that but that doesn't seem to work either. I've also tried Using signalr query parameters....
You can use Context.Items to store informations in the scope of a connection.
So you could have an action in your hub that is called when the users input their names and that action stores the user name in the Items. That informations remains available for the duration of the connexion.
public class ChatHub : Hub
{
public void Login(string login)
{
Context.Items["Login"] = login;
}
public async Task SendMessage(string message)
{
await Clients.All.SendAsync(Context.Items["Login"] + "sends the message : " + message);
}
}