I just managed to get my SignalR chat going, and I ran into this problem.
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
$('#chat-body').append('<li><strong>' + name + ' :</strong> ' + message);
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#send-chat-msg-btn').click(function () {
// Call the Send method on the hub.
chat.server.send('Username', $('#message-input-field').val());
// Clear text box and reset focus for next comment.
$('#message-input-field').val('').focus();
});
});
});
</script>
The username is set in this javascript code, when sending to the server.
I don't want that, as people can pretend to be other people by changing their name here.
public class ChatHub : Hub
{
DatabaseContext db = new DatabaseContext();
public void Send(string name, string message)
{
// Get character
string Username = User.Identity.GetUserName();
Character Character = db.Characters.Where(c => c.Name == Username).FirstOrDefault();
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
The name is sent to this ChatHub
But I want the name to be set here instead of the JS code.
But I am not able to get the name from the database cause it says User does not exist in the current context
How can I set the name here in the model, instead of in the js code?
Thank you.