0
votes

Hi in my application I am using SignalR to store the user and signalR connection mapping. I am adding connections and user mapping on OnConnected() event and removing connections on OnDisconnected() event.

OnDisconnected event is getting called when a file is downloaded from application, which removes the user connections. Below is the code for file download

 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 or OnConnected events are not get called subsequently, which results is the data loss (user connection mapping stored on OnConnectedEvent). So system does not able to send notification to removed user connection.

Below is the code for SignalR events

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();
    }

Does any one have any idea why onDisconnected event is getting called on File download().

2

2 Answers

0
votes

We temporarily "solved" this by adding target="_blank":

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

But we are still looking for a better solution so we don't need to use target="_blank". So any other solution is much appreciated.

0
votes

Finally I found the solution to the problem: Attach a handler on the disconnected event with the signalR client API and set timeout for few seconds 2 or 3 and reconnect with the hub. This approach will also work if a large file takes time to download because the event will only trigger if the SignalR HUB will disconnects no matter file download takes how much time.

Below is the code

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