Reset session timeout without postback in ASP.Net

Is there a way to reset the session timeout without performing a postback?

In this scenario, I do not just want to hide the postback from the user, I need to reset the timeout with the postback.

On my page, I need to open a dialog and tell the user that his session is disconnected, and if he wants to keep him alive, he needs to click on the button. Now, when he clicks on this button, I do not want to return the page, because this will cause data problems. (Without getting into trouble)


Based on the answers, I changed the code, but it still does not work. docs.google.com/open?id=0B-Pl5DH2W9MvMDV6SUNiTXR0Z2M

+1
source share
3 answers

To update the session you need to make a call - I suggest a simple handler that just shows an empty gif. Here is a simple code for this:

public class JustEmptyGif : IHttpHandler ,IRequiresSessionState 
{
    // 1x1 transparent GIF
    private readonly byte[] GifData = {
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
        0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
        0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
        0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
        0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    };  

    public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType = "image/gif";
        context.Response.Buffer = false;
        context.Response.OutputStream.Write(GifData, 0, GifData.Length);        
    }

    public bool IsReusable 
    {
        get {
            return false;
        }
    }
}

This code is just a handler, let’s say EmptyImage.ashxand note that I have included IRequiresSessionStatewhich make it invoke and update the session.

Now all you have to do is update the hidden image using a script like:

<img id="keepAliveIMG" width="1" height="1" alt="" src="EmptyImage.ashx?" /> 
<script>
var myImg = document.getElementById("keepAliveIMG");
    myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
</script>

I put a random number at the end to avoid caching it and making it reload it again. There are no messages, only a small image download.

+4
source

The only way I can come up with is to make ajax call to the dummy .net page as follows:

function keepAlive()
{
var xmlHttp = null;

xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "KeepAlive.aspx", false );
xmlHttp.send( null );
}

and then call it like this

<input type=button onClick='keepAlive();' >
+1
source

Here are some useful suggestions: How to save an ASP.NET session .

0
source

All Articles