SignalR onDisconnected(bool stopCalled)在MVC中调用文件下载
问题描述:
嗨,在我的应用程序中,我使用SignalR来存储用户和signalR连接映射。我在OnConnected()事件和删除连接OnDisconnected()事件上添加连接和用户映射。SignalR onDisconnected(bool stopCalled)在MVC中调用文件下载
从应用程序下载文件时会调用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事件获取调用的文件下载()。
答
最后,我找到了问题的解决方案: 使用signalR客户端API在断开连接的事件上附加处理程序,并将超时值设置为2或3秒,然后重新与集线器连接。如果一个大文件需要花费时间下载,这种方法也可以工作,因为无论文件下载需要多少时间,只有当SignalR HUB断开连接时才会触发事件。
下面是代码
connection.hub.disconnected(function() {
setTimeout(function() {
//Connect to hub again
$.connection.hub.start();
}, 3000);
});
答
我们暂时“解决”这个加入目标=“_空白”:
<a href="@Url.Action("DownloadFile", "Controller")" target="_blank"></a>
但我们仍在寻找更好的解决方案,所以我们并不需要使用target =“_空白”。 因此,任何其他解决方案非常感谢。
嗨CDS,我已经发布了解决问题的方法,它的正常工作,这是一个时间集中配置。 –