How can i get the current username in Session_End in Global.asax RRS feed

  • Question

  • User1092673039 posted

    in the Session_End event, i'm trying to get the current username by using  

    but it seems the HttpContext.Current is null. So I try to set session variable (in validateUser membership overriden class) by using 
    but it seems the HttpContext.Current is null too. How or what can i do?
    Y does the httpContext.Current is null in session end? 
    Wednesday, July 18, 2007 10:50 PM


All replies

  • User1825434375 posted

     I think this is due to that HttpContext is valid only for the request processing. Session_End event is getting called separately from any requests, so that no HttpContext exists.

    Thursday, July 19, 2007 3:30 AM
  • User1092673039 posted

    o, ic.

    so how do i get the current username for that session then ???



    Thursday, July 19, 2007 4:08 AM
  • User1825434375 posted

    Did you try to use HttpApplication.Session property?

    Thursday, July 19, 2007 4:48 AM
  • User-1091210821 posted

    You cant, because it not guaranteed to be executed, unless you save your session in sql server--inproc. So atleast you will know the event is firing. In my opinion that should return a null anyways..

    Thursday, July 19, 2007 6:36 AM
  • User1092673039 posted

    ArtemL: i'm not sure but i think i already tried Session["username"] <== this also return null in global. I'll try what u suggest and return the answer THX.

    remark, i tried to set the username in .dll not in the page, thus some object cannot be referneced in the library.


    naturehermit: if i can't do logoff in session_end, what actully should be in there then??? could u give me some idea or concept of this event? THX



    Thursday, July 19, 2007 10:20 AM
  • User-1091210821 posted

    What I meant was that current username ins session_end event in globals.asax will return null as the user would not exist for session_end event to fire.

    As long as you are in InProc session state, it should fire.  If the session state is set to use a state server or SQL Server, session_end will never fire.

    Unfortunately there isn't a really easy way to-do this - since the Session_End event isn't always guarenteed to fire and so you need to be careful about what assumptions you make on it.

    Probably the easiest way to implement this would be to write your own custom HttpModule that you plug into ASP.NET

    Thursday, July 19, 2007 10:42 AM
  • User1092673039 posted

    I strongly agree with you and found that when the user closes the brower the session_end does not fire but if time out it does. So i understand ArtemL's first qoute that maybe there's not the request sent to server make the session_end doesn't fire too.

    but when i navigate back to the page which has Logoff button i still can get the current user name from that page request (may be the cookies still alive). so i wonder what if i want to logoff the current user in this case (timeout) what should i do. Transfer to logout page and let the logout page get the current user ? or what else i can do.

    what does the real world normally do when time out?

    P.S. my system will not kick off the current user if second session (with same ID) is logging in. the first one is priority that's y we must need logoff function to allow the second session.


    Thursday, July 19, 2007 11:31 AM
  • User-1091210821 posted

    What is it that you would like to do at this point in time??

    Monday, July 23, 2007 4:47 AM
  • User1092673039 posted
    I want to logoff user. eventhough it's time out server needs to log the user off otherwise the user cannot login anymore.
    Monday, July 23, 2007 6:14 AM
  • User-1091210821 posted

    And what conditions you are looking for??? (to logg off the user). Please put all the requirement and lets just sort this out.

    Monday, July 23, 2007 6:19 AM
  • User1092673039 posted

    What do u mean by conditons???

    However, think like this.

    I'm making an application for internal used over the internet tha need user authitication, i'm using form authen then,

    Then when they r accessing the server will make that one is online. <-- logged in

    next next when the user wan to leave, server must be noticed that the user is leaving thus clear the online flag. <-- logged out

    the logoff operation might be fired when

    1. user action logoff

    2. user close the browser

    3. form authentication time out

    choice 1 is simple then leave it.

    choice 2 i can do it now with a trick user logout page redirection. send command logoff from logout page

    but choice 3 i think it's already in at the server side which the server should now the currect session is running out of time, but when i try to use the http.current the username is null. why ?????

    that's ok why, actully i want to know how to get user name by other ways.

    thz for keeping helping [cool]

    Monday, July 23, 2007 7:07 AM
  • User-1091210821 posted

    The parameter userIsOnline, when set to True, will update a timestamp in the data store indicating the date/time the user was last requested. This timestamp can then be used to calculate the total number of users online.<SUP> </SUP>The remaining methods will perform similar operations but on a specified user.



    GetUser() As MembershipUser

    GetUser(userIsOnline As Boolean) As MembershipUser
       GetUser(username As String) As MembershipUser
       GetUser(username As String,
       userIsOnline As Boolean) As MembershipUser

     Fetching the Logged-on User


    use Session_end event in Global.asax and this will work whenever a user session dies, which will happen as soon as the user closes the browser (all sessions will die..)

    protected void Session_End(Object sender, EventArgs e)
                if(Session["ID"] != null)


    To make this work with login, set session[id] to null when the user logs out, and set the session whenever the user is in..either by login or cookies..i.e. after user is authenticated.

    However these should be used with caution because keep in mind that there are some circumstances in which this event might not

    * If the session is terminated manually (for instance you click the stop
    button in Visual Studio.)
    * If you are not using the standard in proc sessions (i.e. you're using SQL
    Server to store state.)

    I believe there are a few other obscure things that could prevent it from
    firing too, so take this into account when designing your solution by having
    some kind of cleanup routine to handle any sessions that slip through the

    Here is a link to make sure all that doesnt happen


    <%@ Page Language="VB" %>

    <script runat="server">

      Public Sub Page_Load()
        Dim user As MembershipUser

        ' Get the currently logged-on user and
        ' update the user's online timestamp
        user = Membership.GetUser(True)

        UserName.Text = user.Username

      End Sub



      <body style="FONT-FAMILY: Verdana">

      <H1>Get User</H1>

      <hr />

         <form runat="server">
           The currently logged-on user is:
           <asp:literal id="UserName" runat="server" />




    If HttpContext.Current.User IsNot Nothing AndAlso _
       HttpContext.Current.User.Identity.IsAuthenticated AndAlso _
       TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
    sCookieName As String = FormsAuthentication.FormsCookieName
      If Request.Cookies(sCookieName) IsNot Nothing AndAlso Request.Cookies(sCookieName).Value <> "" AndAlso _
        (Session("LastLogin") Is Nothing OrElse Context.Session("LastLogin").ToString = String.Empty) Then
    cust As New helperclasses.Customer
        Session("LastLogin") = Date.Now
      End If
    End If

    Monday, July 23, 2007 10:47 AM
  • User1092673039 posted

    yes, i override the membership method connect to oracle database. the userIsOnline seem to be the time slide  if the user didn't refresh anything on page. lastupdate time will be stamp whenever GetUser/NewUser/GetProfiles/Updateuser/ValidateUser and this is not applied for user close the browser. I don't know what did i miss but when the user closes the browser session_end didn't fire. the result is the session will wait for timeout to kick off the user though (or just disappear).

     I will try ur code tommorow (my day time ;)) to see this is help for user close window and session variables and give u te result i found.

     Now what i try to do is to put the session["userName"] on base page to prepare firing event from server and do the logoff at redirect page. which i'm not happy with that.

    Session in Session_end is null,,, this is my point.

    P.S. I'm using cookiesless.


    1. what's the idea that u all can see the session variable while i can't ??

    2. how do i know that i'm not using in-proc??



    Monday, July 23, 2007 11:12 AM
  • User-1091210821 posted

    Answers :P

    1. Depends where you access the session variables, you can or you cant see the session variables.

    The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.

    1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.

    2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.

    3. Raise the BeginRequest event.

    4. Raise the AuthenticateRequest event.

    5. Raise the PostAuthenticateRequest event.

    6. Raise the AuthorizeRequest event.

    7. Raise the PostAuthorizeRequest event.

    8. Raise the ResolveRequestCache event.

    9. Raise the PostResolveRequestCache event.

    10. Based on the file name extension of the requested resource (mapped in the application's configuration file), select a class that implements IHttpHandler to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.

    11. Raise the PostMapRequestHandler event.

    12. Raise the AcquireRequestState event.

    13. Raise the PostAcquireRequestState event.

    14. Raise the PreRequestHandlerExecute event.

    15. Call the ProcessRequest method (or the asynchronous version BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.

    16. Raise the PostRequestHandlerExecute event.

    17. Raise the ReleaseRequestState event.

    18. Raise the PostReleaseRequestState event.

    19. Perform response filtering if the Filter property is defined.

    20. Raise the UpdateRequestCache event.

    21. Raise the PostUpdateRequestCache event.

    22. Raise the EndRequest event.

     The Session is not available until AcquireRequestState.

    2. The following makes your session inproc 


    http://msdn.microsoft.com/en-us/library/ms972429.aspx There is always the option of storing the session in sql server. However some pundits do not like inproc http://west-wind.com/weblog/posts/1986.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 24, 2007 4:27 AM
  • User1092673039 posted

    Depends where you access the session variables, you can or you cant see the session variables.

    i already try

    protected void Session_End(Object sender, EventArgs e)
                if(Session["ID"] != null)

    but the session is null (in watch mode), how different between u and me.

    by the way, or i need to assign the session in global.asax too????

    I already tried to assign the session variable at ValidateUser (membership class) and login page, the result is the same, so i wonder y u can use session in session_end?????  

    Thank you so much for ur last post, it's useful for my other case [:)].


    Tuesday, July 24, 2007 7:17 AM
  • User-1091210821 posted

    Lol atleast im of some help.

    so you got it set to inproc--??

    Tuesday, July 24, 2007 7:23 AM
  • User1092673039 posted

    so you got it set to inproc--??

    i think i do coz i didn't set anything to sessionstate, only timeout.

    Tuesday, July 24, 2007 8:42 PM
  • User1260035262 posted

    Hi spncc!!

     did you ever got this working? I am in the same boat. Is there any way to get userName in session_End event???

    Please reply


    Sunday, March 9, 2008 12:26 PM
  • User1092673039 posted

    yes BhaveshPatel,

    I assign SESSION["ID"] at page load by using

    if (Page.User.Identity.IsAuthenticated)
    Session["ID"] = username;
    and also in the session_End u need to check 
    if (Session["ID"] != null) 
    'coz it sometimes fires this trigger without authentication

    the reason why isAuthen is the username is avalilable only if the user is authenticated otherwise it will be null (I don't know if u r using anonymous)

    the reason why i put it in Logon Page Load is i'm using Form authen that the unAuthen user must be redirect to login page.

    and don't forget to set the session time mpre than authetication time otherwise session will be expired when the triger is fire.  


    glad if this can help :)


    Sunday, March 9, 2008 11:26 PM
  • User604186779 posted

    I am also stucking with this

    I can't able to get the Username on Global.asax file

    Let any have Solution ?????

    Wednesday, August 19, 2009 1:39 AM