我剛剛設法讓我的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代碼?
謝謝。
你能展示如何使用HubCallerContext嗎?我不明白。 –
Hub類有一個Context屬性,它是HubCallerContext的一個實例。所以你只需在你的Hub類中使用Context.User。 –
好,但我得到了NullReferenceException,所以我必須先在某處設置名稱? –