Reset session timeout without doing postback in ASP.Net

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 23:34:56

问题


Is there any way to reset the session timeout without doing postback?

In this scenario I don't just want to hide the postback from user, I need to reset the timeout with out postback.

On my page I need to popup a dialog and inform the user that his session is timing out and if he wants to keep it alive he needs to click on a button. Now, when he clicks on that button I do not want to postback the page because it will cause issues with the data. (Not getting into the issues)


Based on the answers I have modified the code but it's still not working. docs.google.com/open?id=0B-Pl5DH2W9MvMDV6SUNiTXR0Z2M


回答1:


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

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 say EmptyImage.ashx and notice that I have include the IRequiresSessionState that make it to call and update the session.

Now the only think that you have to do is to update a hidden image with some script, as:

<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 have place the random number at the end to avoid to keep it on cache and force it to reload it again. No post back happens here, just a small image load.




回答2:


Only way I can think of is to do an ajax call to a dummy .net page like this:

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



回答3:


There are a number of helpful suggestions here: How To Keep ASP.NET Session Alive.



来源:https://stackoverflow.com/questions/13997778/reset-session-timeout-without-doing-postback-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!