Search code examples
asp.netsessionexceptionsession-state

Session state can only be used when enableSessionState is set to true, When i use Server.Transfer


Each Page in a website including Error page is Derived from Master page. In Master Page I am accessing the Session variables. When i get the Exception, handling in Page_Error or Application_Error Events. From there i am redirecting to the Error page using Server.Transfer, then i am getting this below exception in master page of Error.aspx. if i use Response.Redirect it works properly.

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

please explain whats the problem with Server.Transfer in Detail.


Solution

  • when application throws the exception, i am handling in Application_Error event.

    protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();
            if (ex.Message == "File does not exist." && HttpContext.Current.Session == null)
            {
                if (((System.Web.HttpException)(ex)).GetHttpCode() == 404)
                {
                    LogtheException();
                }
            }
            else
            {
                Log the Exception(Session["uname"].ToString());
                Server.Transfer(UrlMaker.ToError(ex.Message.ToString()));
            }
        }
    

    Using HttpContext.Current.Server.GetLastError(); i am getting the last exception. If any exception, other than "File does not exist." is having the access to session variable.

    First it throws exception related to application, then if any css/image file path is not correct then immediately next it throws the "File does not exist." exception. The exception is because of not handling the sessions properly for "File does not exist." case.

    Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.
    

    Now I came to know that Css and image requests normally don't need to access the session, therefore asp does not load the session into memory and you don't have access to it on exception "File does not exist."..