开发者

Keeping session alive C#

I'm using HttpWebRequest to log on to a website and get the session cookie. My application scrapes certain pages, 开发者_开发百科and eventually becomes idle, resulting in the session dying.

What would be a good way to prevent this and -just being curious- how do web browsers do it?


Browsers by themselves don't do this at all. They only do so if the Web App itself builds in support for it. For example there might be some javascript which makes an AJAX request every 30 seconds or so to send a "keep-session-alive" type request to the server, which would then go and update its state information to reflect that the "most recent activity" was now, and hence prevent a session timeout.

In the example above however, the "client" i.e. html/javascript in the browser, and the "server" would have been written together and thus this type of functionality built in.

If you aren't responsible for the server-side app, and thus can't build the "keep-alive" functionality into it yourself, your best bet would be to either physically go to the web-page, look through all the javascript to try to find possible "keep-alive" code (look for SetTimeout, SetInterval or related methods in any js frameworks they may be using). Of course there might not be any such functionality, in which case your best bet is to simply "refresh" the page you are on (i.e. send the same request again)


You can't prevent it as such, unless you keep the session active by requesting a particular resource of the website in question at certain fixed intervals, say every 10-15 minutes.


Client-side: Call the server every x-minutes, just be sure it's not too often. Best would be to go just under the session time-out value:

(Javscript / Jquery)

$(function() {
        setInterval(function() { $.post("/KeepSessionAlive.ashx", null, null); }, 60000 );
    });

Server-side: In the KeepSessionAlive file on the server you write something to the session, fe:

context.Session["KeepSessionAlive"] = DateTime.Now;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜