How to trigger a method when session timeout is completed? - c#

I've a method which logs user activities in the database, I need to capture the logout activity but in our website there's no logout functionality so i want to trigger this user activity method when the session timeout occurs or when the browser is closed. I've tried calling this method from Session end method, but it dint work

you can handle on Session_End in Global.asax file
protected void Session_End(Object sender, EventArgs e)
{
// Remove user from HashTable
}
this method only call when Session Is get Timeout
only way to track the browser closing is Js
and for this purpose This link should help you

Related

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

Redirect from Global.asax

HttpContext.Current.Response.Redirect("~/default.aspx");
When i use this code in session_end in global.asax
error to me:
Object reference not set to an instance of an object.
why?!
Session_end is not an event that gets called by the user of your application, it's something that gets called by the server when a session times out. So when you try to access HttpContext, it is null because there is no HttpContext to access (no user who is currently performing some kind of interaction with your site).
Your attempt to redirect a non-existing HttpContext will always fail no matter what you do.
When the event SessionEnd is raised the Request and then the Response are null.
HttpContext.Current.Response //this is null
This is by design: Session ends not during a request but when the session timeout
It usually (default config) happens 20 minutes after the last request.
Since there is no request there is also no response.
You need to understand better how Asp.net Session State works
Anyway if you want to redirect the user to a page if the Session is expired you can check for one of your variables stored on session:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["YOUR_VAR_NAME"]==null)
{
Response.Redirect("~/default.aspx");
}
}
Session_End is fired internally by the server, based on an internal timer. Thus, there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.
I hope the above information will be helpful

ASP.NET MVC4 - Session_End - How can I get the currently logged on user's name in Session_End of Global.asax?

My issue is that once Session_End executes in my Global.asax, the HttpContext.Current object no longer exists- probably as expected, I would imagine. So, what I'm trying to do is once the session ends, update my Logins table for the user currently logged in and set their LoggedIn status to False. Here's my Session_End:
protected void Session_End(object sender, EventArgs e)
{
Helpers.OperationContext.UpdateIndividualLogin();
}
As you can probably guess, I can try to pass in:
System.Web.HttpContext.Current.User.Identity.Name
But this object no longer exists because I can only imagine that it's already been disposed of. So, is there any way I can grab the currently (or previously current) user's name?
You can do this by storing the information you want (in this case the user name) in Session. You can store it when the user is authenticated.

Is this possible to clear the session whenever browser closed in asp.net?

In my asp.net application, i want to clear the session whenever my browser closed or my tab (if my browser containing multiple tabs)closed.
Please guide me to get out of this issue...
Short version, No.
There's no solid way of a server detecting if the client has closed their browser. It's just the nature of web development's asynchronous pattern.
Long version, if it's really, really important to you;
Put a bit of javascript in the page that sends a regular post to your website in the background and set up a serverside agent or service that disposes of the sessions if it doesnt receive these regular "heartbeat" signals.
You can put a javascript postback onto the page's unload() event but dont rely on it, it doesnt always fire.
This happens by default whenever you close your browser, and that's not just for ASP.NET. It's for most server-side programming languages that have a session state. Basically, any cookie that is added that doesn't specify an expiration date, will be deleted when the browser is closed.
Where this doesn't apply, is when you close a tab, which is something you will not have any control over because the tab close event will not get sent back to the Web server.
You can try to do that with javascript. Check it at:
http://www.codeproject.com/Tips/154801/How-to-end-user-session-when-browser-closed
Alternatively you can check you previous session state on every new browser opening and can Session.clear() or Session.abandon() the previous session.
this will make sure that every time you start application you will get new session.
use BasePage in your .net application.
Check the session.sessionid on basepage load.
More Inforamtion how to detect new session in basepage. BasePage.Session.Link
Hope this helps
regards
Shaz
public class BasePage : Page
{
protected string mySessionId;
private CurrentUser _currentUser;
public CurrentUser _CurrentUser
{
get { return ((CurrentUser)HttpContext.Current.Session["myCurrentUser"]); }
set { _currentUser = value; }
}
protected override void OnLoad(EventArgs e)
{
if (Session["myCurrentUser"] != null)
{
if (_CurrentUser.ProUser)
{
mySessionId = Session.SessionID; // it means New Session
}
if (!mySessionId.IsNullOrDefault() && mySessionId != Session.SessionID)
{
Session.Abandon(); //Abandon current session and start new one
}
}
}
}
I think cookies can better meet your requirement here for session management.
it means that session data should not be stored on the server and
should be with your call, so that you don't have to worry about
clearing the data on server.
Yes.First of all Browser automatically clear session when browser is closed. you can try to capture browser close or tab close event in browser using javascript function like on before unload and on unload. Mostly onbefore unload event captures browser close event in chrome, Firefox, IE 11.
You can use Session_End event of Global.aspx
//For Specific Session
Session.Remove("SessionName");
//All the Session
Session.Abandon();

Using Cache ASP.NET

How can I use Cache in ASP.NET which is accessible by all users not just a specific user context while having a specific key of this cache removed automatically when a user closes the browser window or expires (like a session object) ?
Cache is accessible to all users, you can set it to expire after a period of time:
Cache.Insert("key", myTimeSensitiveData, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero);
You may remove the cache entry whenever a session expires by implementing the global.asax's session end event
void Session_End(Object sender, EventArgs E)
{
Cache.Remove("MyData1");
}
See this for more details on Cache
Edited:
Regarding your question on how to react when the user closes its browser, I think that this is not straightforward. You could try javascript on the client side to handle the "unload" event but this is not reliable since the browser/client may just crash. In my opinion the "heartbeat" approach would work but it requires additional effort. See this question for more info.
You'll have to use the Session_OnEnd() event to remove the item from the cache. However, this event will not fire if the user just closes the browser. The event will only fire on the session timeout. You should probably add a check to see if the item has already been removed:
public void Session_OnEnd()
{
// You need some identifier unique to the user's session
if (Cache["userID"] != null)
Cache.Remove("userID");
}
Also, if you want the item in the cache to stay active for the duration of the user's session, you'll need to use a sliding expiration on the item and refresh it with each request. I do this in the OnActionExecuted (ASP.NET MVC only).
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Put object back in cache in part to update any changes
// but also to update the sliding expiration
filterContext.HttpContext.Cache.Insert("userID", myObject, null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(20), CacheItemPriority.Normal, null);
base.OnActionExecuted(filterContext);
}

Categories