2016-06-10 52 views
0

我剛剛設法讓我的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代碼?

謝謝。

回答

1

通常在MVC中,如果你不在控制器中,你想使用HttpContext.Current.User.Identity。儘管如此,這對於集線器無法正常工作 - 如果您仔細考慮,集線器有很多連接,並且不一定在特定用戶的HTTP環境下運行。相反,您應該使用HubCallerContext上的用戶屬性。

請注意,只有當您的集線器配置爲使用身份驗證時,纔會填充它 - 否則服務器無法知道客戶端的用戶名。見here。如果您使用OWIN進行自託管,則需要在調用MapSignalR之前配置auth模塊(請參閱this answer)。

+0

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

+1

Hub類有一個Context屬性,它是HubCallerContext的一個實例。所以你只需在你的Hub類中使用Context.User。 –

+0

好,但我得到了NullReferenceException,所以我必須先在某處設置名稱? –

相關問題