Prolonging asp.net session enddate? - c#

How is asp.net Session prolonging, does every request prolongs the end date of Session, and is it enough to call void() by ajax to extent Session end date by another period of time(default 20 min or so...)
public void ResetSessionTime()
{
}
or do i have to invoke session in some way:
public void ResetSessionTime()
{
User currentUser = HttpContext.Current.Session[userSessionKey] as User;
}
how does simple request extend session end date?
This question claims every post-back prolongs session...
This MSDN about Session State Providers :
"Each session created by ASP.NET has a timeout value (by default, 20
minutes) associated with it. If no accesses to the session occur
within the session timeout, the session is deemed to be expired, and
it is no longer valid."
How does request access the session exactly?
THIS QUESTION: Keeping session alive C# does not answer how session end date is prolonged by request, only a opinion on how to keep session alive from client side
EDIT:
According to this article, method needs to be extended from IHttpHandler, in order to access current session...
public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Session["KeepSessionAlive"] = DateTime.Now;
}
}

Every time you make a request, the session timeout is reset. A request can be a page load or something like an ASYNC call.
Take a look at this question for an example of how to keep the session alive by periodically making AJAX calls to the server. (Keeping ASP.NET Session Open / Alive)

Related

ASP.NET Webservice- SessionState not timingout

I have a web application that utilizes JQuery as my front end code and ASP.NET as my backend web service.
I set the web.config setting <sessionState timeout="1">. When the user logs in, the web service creates a session variable with the user name.
System.Web.HttpContext.Current.Session["UserID"] = user_id;
In my web service, I have a function that checks if the variable still exists.
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public string GetSessionUserID()
{
string user_id = "";
if (System.Web.HttpContext.Current.Session["UserID"] != null)
{
user_id = System.Web.HttpContext.Current.Session["UserID"].ToString();
}
return user_id;
}
I have a JS function that calls the web service that calls GetSessionUserID().
$(document).ready(function () {
getSessionID();
setInterval(getSessionID, 3000);
function getSessionID() {
console.log("getSessionID");
$.ajax({
url: "photoapp.asmx/GetSessionUserID",
//data: ,
success: OnGetSessionIDSuccess,
error: OnGetSessionIDError
});
}
function OnGetSessionIDSuccess(data, status) {
console.log("Success OnGetSessionIDSuccess");
console.log(data);
var strUser = $(data).find("string").text();
console.log(strUser);
if (strUser == "") {
window.location = "login.html";
}
}
}
In the document ready function, I also call setInterval() which will check the session every 3 seconds.
When testing, getSessionID gets called every 3 seconds, but after a minute, the getSessionID user variable can be found. I want the redirect the user back to login.html after the minute is done. Why is the session variable still alive after a minute? What am I not understanding about ASP.Net session state? How can this be fixed?
Be aware that if you adopt SQL server to save the session state, then the session timeout events never get called, and you thus can't know or tell if the user actually has logged out.
The only possible solution then is to ensure that all web pages have some kind of heartbeat or routine that calls the server every minute or so, and when that stops, then you know the user is gone or closed the web page.
In your case? If you touch the server every 3 seconds, then the session timeout will be re-set and start over with 1 minute. You also don't mention if you using in-memory, or using sql server for session state.
If you want to jump back to the logon page? Then your 3 second js code has to get/grab the time of the last heartbeat you call every 3 seconds. So, that routine has to set a start time, and then every 3 seconds check the elapsed time. Keep in mind that if you use sql sessions, then not even the logon event will fire, nor will even the authenticated user event fire.
So, the first time you start running that routine, you need to set a session value with the start time.
However, to my knowledge, every web service call will re-set the session time out to start over to 0. session timeout gets re-set when no activity occurs. So, if the user is doing something (or your ajax calls are), then session timeout will never occur.
You have to set a start time. And then get the elapsed time from that. You session will never timeout as long as you have the web page hitting and talking to the server.

Asp.net MVC Session timeout condition based handling

My MVC web application uses asp.net session management. Session has default timeout 20mins. On session timeout, user is redirected to the home page. My application uses SessionTimeout ActionFilterAttribute to handle session timeout.
SessionState is stored in server.
Problem:
Even if the session timout happens, when the user returns to a particular action method, I need to renew a session for that user and allow to continue instead of redirecting to home page.
I have tried to use the OnActionExecuting method in the SessionTimeout ActionFilterAttribute to identify the session timeout & if the action in the request is that particular action method, then allow the user to continue to that action.
But it seems to be not working. It just redirects the user to the Home page.
I am not sure how to proceed.
Session have bad problems like timeout and refresh not available, do authentication using forms authentication you can choose this custom authentication sample
Or Else use cookies
HttpCookie MyCookie = new HttpCookie("MyCookie");
// for remveing if already Exists adding new;
Request.Cookies.Remove("MyCookie");
if (Request.Cookies["MyCookie"] == null)
{
MyCookie["id"] = id.ToString();
Response.Cookies.Add(MyCookie);
}
else
{
MyCookie["id"] = id.ToString();
// Request.Cookies.Remove("MyCookie");
Response.Cookies.Set(MyCookie);
}
// retries
int id = Convert.ToInt32(Request.Cookies["MyCookie"]["id"]);
Thanks for your responses.
"Session cannot be renewed" once it has expired.
Instead of renewing the session, create a new session in the ActionFilters Attribute (SessionTimeout).
The solution for my problem is to create a new session and re-link it with the domain object/user so that the user can continue his journey. I have done this in my SessionTimeout ActionFilterAttribute, to create new session for only a particular request which has the particular controller/action.

SessionID changing at every page call

I'm accessing the SessionID using this code in my class:
HttpContext.Current.Session.SessionID;
however I find that SessionID changes at every page postback, this happens in a short time, so the current session should not expire already. I supposed that the SessionID to remain the same for the whole time until expired.
When using cookie-based session state, ASP.NET does not allocate
storage for session data until the Session object is used. As a
result, a new session ID is generated for each page request until the
session object is accessed. If your application requires a static
session ID for the entire session, you can either implement the
Session_Start method in the application's Global.asax file and store
data in the Session object to fix the session ID, or you can use code
in another part of your application to explicitly store data in the
Session object.
like
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
You should Use the Session_Start method in the application Global.asax file. Below Link may help you
ASP.NET: Session.SessionID changes between requests

will httpcontext.session stay active if read?

I know that Httpcontext.Session in MVC C# has a default timeout period of 20minutes.
But what if is read every 10minutes? Will this extend the timeout period? Or will it still time out after 20mins even if it is read within the 20minutes?
and part 2#. assuming the httpcontext will not time out if it is read within the timeout period, Is it ok to store a dbcontext in a httpcontext.session?
code like this:
public GenericDal()
{
if (HttpContext.Current.Session["unitOfWorks"] == null)
{
unitOfWorks = new UnitOfWork();
HttpContext.Current.Session.Add("unitOfWorks", unitOfWorks);
}
else
{
unitOfWorks = (UnitOfWork)HttpContext.Current.Session["unitOfWorks"];
}
}
It uses a sliding expiration, so when you access it, the timeout gets extended.
A session is considered active as long as requests continue to be made
with the same SessionID value. If the time between requests for a
particular session exceeds the specified time-out value in minutes,
the session is considered expired. Requests made with an expired
SessionID value result in a new session.
https://msdn.microsoft.com/en-us/library/vstudio/ms178581(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
And I wouldn't put the context in the session. The discussion about DBContext in the session is well documented -
One DbContext per web request... why?

How can I handle forms authentication timeout exceptions in ASP.NET?

If the session has expired and the user clicks on a link to another webform, the asp.net authentication automatically redirect the user to the login page.
However, there are cases when the user does not click on links to other webforms. For example: edit link in gridviews, when using AutoCompleteExtender with textboxes and the application attempts to get the information, and basically, in every case when a postback is done and the event is not automatically handled by the asp.net authentication.
What is the best way to handle these exceptions?
UPDATE: I have just modified the question title: forms authentication timeout, instead of the initial session timeout. Thanks for making me aware of this difference.
UPDATE: I have just created a new question with the specific problem I am facing: How to handle exception due to expired authentication ticket using UpdatePanel?. Surprisingly, I have not found much information about it. I would really appreciate your help.
This is why many systems include timers on the page to give approximate timeout times. This is tough with interactive pages. You really need to hook ajax functions and look at the return status code, which is a bit difficult.
One alternative is to use code based on the following which runs early in the page lifecycle and perform an ajax redirect to a login page. Otherwise you are stuck trying to intercept the return code from ajax and in asp.net where the ajax is done 'for you' (ie not a more manual method like jQuery) you lose this ease of detection.
http://www.eggheadcafe.com/tutorials/aspnet/7262426f-3c65-4c90-b49c-106470f1d22a/build-an-aspnet-session-timeout-redirect-control.aspx
for a quick hack you can try it directly in pre_init
http://forums.asp.net/t/1193501.aspx
Edit
what is wanted are for forms auth timeouts, not session timeouts. Forms auth timeouts operate on a different scale than session timeouts. Session timeouts update with every request. Forms auth tickets aren't actually updated until half of the time goes by. So if you have timeouts set to an hour and send in one request 25 minutes into it, the session is reset to an hour timeout, the forms auth ticket isnt touched and expires in 35 minutes! To work around this, sync up the session timeout and the forms auth ticket. This way you can still just check session timeouts. If you don't like this then still - do the below and sync up the timeouts and then parse the auth ticket and read its timeout. You can do that using FormsAuthentication.Decrypt - see:
Read form authentication cookie from asp.net code behind
Note that this code requires that upon login you set some session value - in this case its "UniqueUserId". Also change the login page path below to fit yours.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Only access session state if it is available
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
//If we are authenticated AND we dont have a session here.. redirect to login page.
HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authenticationCookie != null)
{
FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
if (!authenticationTicket.Expired)
{
if (Session["UniqueUserId"] == null)
{
//This means for some reason the session expired before the authentication ticket. Force a login.
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx", true);
return;
}
}
}
}
}
If you're using Forms Authentication, the user will be redirected to the login page when the Forms Authentication ticket expires, which is not the same as the Session expiring.
You could consider increasing the Forms Authentication timeout if appropriate. Even to the extent of using a persistent cookie. But if it does expire, there's no real alternative to redirecting to the login page - anything else would be insecure.
One way to deal with Session timeouts is to use Session as a cache - and persist anything important to a backing store such as a database. Then check before accessing anything in Session and refresh if necessary:
MyType MyObject
{
get
{
MyType myObject = Session["MySessionKey"] as MyType
if (myObject == null)
{
myObject = ... get data from a backing store
Session["MySessionKey"] = myObject;
}
return myObject;
}
set
{
Session["MySessionKey"] = value;
... and persist it to backing store if appropriate
}
}
If you're using a master page or a base page, I would add some logic to one of the events in the page lifecycle to check whether the session is new:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.IsNewSession)
{
//do whatever you need to do
}
}

Categories