Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use post to keep session alive?

Tags:

jquery

c#

session

I'm developing a web application with C# MVC and using Session to persist data between multiple requests.

Sometimes the session timed out so I looked for way to keep it alive and found some solutions here in stackoverflow. Being reluctant to simply copy-paste code into my project I attempted to rewrite the code to fit my needs and understand it better.

At first I attempted to keep the session alive using the following code:

JS + jQuery - client side:

function keepAliveFunc(){
    setTimeout("keepAlive()", 300000);
};

function keepAlive() {
    $.get("/Account/KeepAlive", null, function () { keepAliveFunc(); });
};

$(keepAliveFunc());

C# - server side:

[HttpGet]
public bool KeepAlive()
{
    return true;
}

This however did not seem to keep my session alive, it expired normally. After a while of fiddling around I changed the code to:

JS + jQuery - client side:

function keepAliveFunc(){
    setTimeout("keepAlive()", 10000);
};

function keepAlive() {
    $.post("/Account/KeepAlive", null, function () { keepAliveFunc(); });
};

$(keepAliveFunc());

C# - server side:

[HttpPost]
public JsonResult KeepAlive()
{
    return new JsonResult { Data = "Success" };
}

The latter worked well which has me conclude, with some uncertainty, that the Session is kept alive because of the POST request instead of the GET. Which raises the question: Why do I need to use POST when trying to keep my Session alive? What's the difference? Am I making some other mistake which I do not comprehend?

I've looked for answers but I cannot seem to find any on this matter, merely solutions without much explanation. Reading up on Session on MSDN also didn't help me much. This makes me conclude that there are some "words" related to Session and this perticular problem that I haven't encountered yet which makes me unable to google effectively.

like image 613
Prowling Duck Avatar asked Sep 26 '22 08:09

Prowling Duck


1 Answers

With either GET or POST, the browser does send the SessionId cookie with the request. So for keep-alive purposes it doesn't matter which one you use. Most likely you are seeing the difference in behavior because of the different interval you and "pinging" the server.

With the GET request you did it at an interval of 300000 ms, while with the POST request you did it at an interval of 10000 ms.

Most likely, your server's session lifespan is somewhere between the two values. You could, however, configure the session lifespan to fit your needs (as in increasing it), but keep in mind that expiring sessions is a security feature so try to find a small value that is big enough to let your application work ok, but still allow the session to expire in a safe interval of time.

like image 159
Mihai Caracostea Avatar answered Oct 11 '22 17:10

Mihai Caracostea