SignalR onDisconnected(bool stopCalled)在MVC中下载文件时被调用

SignalR onDisconnected(bool stopCalled) getting called on File download in MVC

您好,在我的应用程序中,我使用 SignalR 来存储用户和 signalR 连接映射。我在 OnConnected() 事件上添加连接和用户映射,并在 OnDisconnected() 事件上删除连接。

从应用程序下载文件时会调用 OnDisconnected 事件,这会删除用户连接。下面是文件下载的代码

 public ActionResult DownloadFile(string fileName)
    {
        // adding time stamp to file name
        fileName = fileName.FileNameWithTimeStamp();

        //Fetch file bytes from TempData
        byte[] fileContent = (byte[])TempData[Constants.ExportedData];
        return File(fileContent, Constants.ExcelContentType, fileName);
    }

随后未调用 OnReconnected 或 OnConnected 事件,结果是数据丢失(存储在 OnConnectedEvent 上的用户连接映射)。因此系统无法向已删除的用户连接发送通知。

下面是 SignalR 事件的代码

public override Task OnDisconnected(bool stopCalled)
    {
        string name = Context.User.Identity.Name;
        //Remove data to cache
        cache.Remove(name.ToLower(),Context.ConnectionId);

        return base.OnDisconnected(stopCalled);
    }


 public override Task OnConnected()
    {
        string name = Context.User.Identity.Name.ToLower();
        if(!string.IsNullOrEmpty(name))
        {               
            cache.Add(name, Context.ConnectionId);
        }
        return base.OnConnected();
    }

有谁知道为什么 onDisconnected 事件在文件下载时被调用 ()。

我们暂时 "solved" 通过添加 target="_blank":

<a href="@Url.Action("DownloadFile", "Controller")" target="_blank"></a>

但我们仍在寻找更好的解决方案,因此我们不需要使用 target="_blank"。 因此,非常感谢任何其他解决方案。

最后我找到了解决问题的方法: 使用 signalR 客户端 API 在断开连接的事件上附加一个处理程序,并将超时设置为几秒 2 或 3,然后重新连接到集线器。如果下载大文件需要时间,此方法也适用,因为无论文件下载花费多少时间,只有在 SignalR HUB 断开连接时才会触发事件。

代码如下

connection.hub.disconnected(function () {
        setTimeout(function () {
            //Connect to hub again
            $.connection.hub.start();
        }, 3000);
    });