I am trying to create a .net core 3.0 SignalR project with Angular as client app. I have established a successful connection between client and server and send messages to all the connected clients. I intend to send messages to a particular user and not to all the connected clients. To achieve that I trying to work with ConnectionId, UserIdentifier and User.Identity.Name.
My server side code/Message Hub
namespace SignalR_server
{
public class MessageHub : Hub
{
public static ConcurrentDictionary<string, string> MyUsers = new ConcurrentDictionary<string, string>();
public override Task OnConnectedAsync()
{
string name = Context.User.Identity.Name;
MyUsers.TryAdd( Context.ConnectionId,name);
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
string garbage;
MyUsers.TryRemove(Context.ConnectionId, out garbage);
return base.OnDisconnectedAsync(exception);
}
public void Send(string msg)
{
string strMessage = string.Empty;
Clients.All.SendAsync("transfermessage",strMessage);
}
public string GetConnectionID()
{
return Context.ConnectionId;
}
public string GetUserIdentifier()
{
return Context.UserIdentifier;
}
public string GetUserName()
{
return Context.User.Identity.Name;
}
public Task SendPrivateMessage(string user, string message)
{
return Clients.Users(user).SendAsync("transfermessage1", message);
}
}
}
Client side / Angular code
public startConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:44363/message',{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
this.hubConnection
.start()
.then(() => {
console.log('Connection Started')
console.log('Connection ID: ')
console.log(this.hubConnection.invoke("GetConnectionID"))
console.log('User Identifier: ')
console.log(this.hubConnection.invoke("GetUserIdentifier"))
console.log('User Name: ')
console.log(this.hubConnection.invoke("GetUserName"))
// console.log(this.hubConnection.invoke("SendPrivateMessage","Myuser","test message"))
})
.catch(err => console.log('Error while connecting: ' + err))
}
Whenever a new client is connected, I can see a value for connectionId but UserIdentifier,User.Identity.Name comes out to be null.
I am not sure why is this happening; am I missing some thing or is something is to be done to define UserIdentifers?
