SignalR 在客户端和服务器之间发送和接收日期时间滴答在传输后给出不同的值

Sending and receiving date time ticks between client and server by SignalR gives different value after transmission

我使用 SignalR 和 ASP.NET MVC 应用程序制作了一个聊天框,所有发送的消息都存储在 Azure 存储服务 table 中。对于 RowKeyPartitionKey 我会等于 DateTime.Now.Ticks.ToString().

为了将条目保存到 table,我也没有问题删除一个条目我没有问题。但是,没有问题不是 100% 正确的。

为了删除消息 (不刷新页面),我还将报价发送回客户端并将其存储在 data-key 属性中。如果用户按下删除按钮,该属性的值会将 I 发送回服务器。

我现在遇到的问题是服务器收到的用于删除该消息的标记与 Azure table 中的标记不同。在这里你有我的代码在中心。

public void Send(string name, string message)
{
    long key = DateTime.Now.Ticks; // → key is equal to 635991085278582583

    Clients.All.BroadcastMessage(key, name, message);               
    _chatService.AddMessage(new ChatMessage(key, name, message));   
}

public void Remove(string key)
{
    _chatService.RemoveMessage(key); // → key is equal to 635991085278582500
    Clients.All.BroadcastRemoved(key);
}

这是 class ChatMessage 中的代码:

public class ChatMessage : TableEntity
{
    public string UserName { get; set; }
    public string Message { get; set; }

    public ChatMessage()
    {
    }

    public ChatMessage(string partitionKey, string rowKey) : base(partitionKey, rowKey)
    { 
    }

    public ChatMessage(long key, string name, string message)
    {
        PartitionKey = key.ToString();
        RowKey = key.ToString();
        UserName = name;
        Message = message;
    }
}

调试我的代码后,我发现我在服务器上收到了 635991085278582500,但是 table 中的 PartitionKey 是 635991085278582583。所以你可以看到键是不同的,我有例外。


对于这里好奇的人,你有我的 JQuery 代码:

var chat = $.connection.chatHub;

chat.client.BroadcastMessage = function (key, name, message) {

    message = encode(message);
    name = encode(name);

    var discussionpane = $("#discussion").eq(0);

    discussionpane.append('<div class="message" data-key="' + key + '"><p><b>' + name + ':</b>&nbsp;' + message + '</p><p>&nbsp;<span class="glyphicon glyphicon-pencil"></span>&nbsp;<span class="glyphicon glyphicon-trash"></span>&nbsp;<span class="glyphicon glyphicon-retweet"></span></p></div>');

    initEvents();
};

chat.client.BroadcastRemoved = function (key) {
    $('.message[data-key=' + key + ']').addClass("removed");
    $('.message[data-key=' + key + '] p').html("");
    initEvents();
};

$('#message').focus();

$.connection.hub.start().done(function () {
    $('#sendmessage').click(function () {

        var text = $('#message').val();

        if (text != "") {
            chat.server.send("@(User.Identity.GetUserName())", text);
            $('#message').val('').focus();
        }
    });

    initEvents();
});

function initEvents() {

    $(".message .glyphicon-trash").click(function () {

        var parent = $(this).parent().parent();
        parent.addClass("removed");
        chat.server.remove(parent.data("key"));
    });
}

找到了!我现在将长值作为字符串发送给客户端。我在客户端收到的值现在等于服务器发送的值。