What actually causes Session_Start to be called?

前端 未结 4 1277
执笔经年
执笔经年 2021-01-17 19:45

In a little demo application that I\'m building I put code to initialize the database in the Global.Session_Start() event. However, I notice that this event does not fire w

相关标签:
4条回答
  • 2021-01-17 20:19

    I know this is an old post but maybe this will help somebody:

    The session_start doesn't fire unless you are actually reading or writing to the session object.

    If you want to utilize the session_start event but don't need to use the session store at all, you can add the following to the page directive of your landing pages:

    <%@ Page EnableSessionState="ReadOnly" %>
    

    This will cause the session_start event to fire without you having to store anything in the session object.

    0 讨论(0)
  • 2021-01-17 20:20

    Hmm..ok. Maybe it would make sense to put the code in BeginRequest() but is there a way to put a handler at EndRequest() at which I can close the database file?

    The issue is that you can never rely on these events to fire, because the ASP.NET runtime decides whether they are fired or not, because they might not even be necessary and can be skipped to save resources.

    For example, a Response.Redirect cancels the whole processing of a request by using a ThreadAbortException, and the page/control lifecycle events after that will not be fired at all, that's why for example there is no End_Request or something similar.

    I would consider moving your logic to a different layer (independent of ASP.NET), and maybe initialize the database when it's actually requested from a page? Then you can close the database file within the same method that you needed the information, this would make you much more independent of the state the application/session is in.

    Not sure if this is the info you were looking for though :)

    0 讨论(0)
  • 2021-01-17 20:21

    What Session Model do you use? In case of SQL Server backed sessions, it may not start a new sessions. In case of InProc, I think it should work. Application_Start has the issue of being sometimes triggered before the debugger can attach, as you pointed out.

    Do you use IIS or the Development Web Server? In case of IIS, this article suggest that you need to create it as an application first.

    0 讨论(0)
  • 2021-01-17 20:40

    I'm not entirely sure that a session "starts" until you access the Session object. Otherwise it would seem like unnecessary overhead to fire up an unneeded session.

    0 讨论(0)
提交回复
热议问题