c# how to set up and use session state from preinit

后端 未结 3 1481
温柔的废话
温柔的废话 2020-12-20 09:56

OK so to set and read variables from the current session

String Myvar =(string) System.Web.HttpContext.Current.Session[“MyVariable”]

To set

相关标签:
3条回答
  • 2020-12-20 10:02

    You can access the session by implementing IRequiresSessionState interface in your class.

    This is a flag interface, so you dont need to implement any extra code.

    When you implement this asp.net will know that you want to access the session.

    public partial class YOUR_ASPX: System.Web.UI.Page , IRequiresSessionState
    {
    
    ... your code
    
    }
    
    0 讨论(0)
  • 2020-12-20 10:16

    To access the session state pre-init you can do something like this. I use it so that I can have a different admin master than the regular user one. Each page has a method at the top.

    PageTools tools = new PageTools();
    protected void Page_PreInit(object sender, EventArgs e)
    {
        tools.setMasterPage(Page, Context);
    }
    

    PageTools is my class that holds the method that chooses the appropriate mater page and has the http handler.

    public void setMasterPage(Page page, HttpContext context)
        /***********************************************************************
         * Author   Daniel Tweddell
         * Date     9/18/09
         * 
         * Several of the pages are for non-admin use, however these pages will
         * also be used by the admin users and will need to have the admin menu
         * and such.  So based on the login, we either show the page with the
         * standard master or if the user is admin, use the admin master.
         ***********************************************************************/
        {
            if (context.Handler is IReadOnlySessionState || context.Handler is IRequiresSessionState)
            {
                context.Handler = Handler();
            }
            String sMasterPage="~/content/page.master";
            if (userinfo.IsUserAdmin) sMasterPage="~/content/administrator/admin.master";//make sure the user is admin
            page.MasterPageFile = sMasterPage; 
        }
    

    Here is a step by step to setting up the httphandler. (which is the other thing you'll need.

    0 讨论(0)
  • 2020-12-20 10:19

    As the comment mentioned, is there some reason you need this in the PreInit event?

    PreInit happens very early in the page lifecycle. It happens, in fact, before even the master page (if any) is applied, before all the controls are fully initialized, etc.

    A much better choice for the majority of applications is in the Load event. If you're still getting a NullReferenceException there, then there's a bigger issue.

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