在模型中设置用户名而不是javascript代码

问题描述:

我刚刚设法让我的SignalR聊天进行,我遇到了这个问题。在模型中设置用户名而不是javascript代码

<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> 

用户名在发送到服务器时设置在此javascript代码中。

我不希望那样,因为人们可以通过在这里改变他们的名字来装扮成别人。

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); 
    } 
} 

名称发送到该ChatHub
但我想的名字在这里,而不是设置的JS代码。
但我不能够从数据库中获取的名字的原因,而是说User does not exist in the current context

我怎么能在这里模型设置的名称,而不是在js代码?

谢谢。

通常在MVC中,如果你不在控制器中,你想使用HttpContext.Current.User.Identity。尽管如此,这对于集线器无法正常工作 - 如果您仔细考虑,集线器有很多连接,并且不一定在特定用户的HTTP环境下运行。相反,您应该使用HubCallerContext上的用户属性。

请注意,只有当您的集线器配置为使用身份验证时,才会填充它 - 否则服务器无法知道客户端的用户名。见here。如果您使用OWIN进行自托管,则需要在调用MapSignalR之前配置auth模块(请参阅this answer)。

+0

你能展示如何使用HubCallerContext吗?我不明白。 –

+1

Hub类有一个Context属性,它是HubCallerContext的一个实例。所以你只需在你的Hub类中使用Context.User。 –

+0

好,但我得到了NullReferenceException,所以我必须先在某处设置名称? –