首页 > 编程 > ASP > 正文

How to Share Session State Between Classic ASP and

2024-05-04 11:06:31
字体:
来源:转载
供稿:网友
applies to:
   microsoft® asp.net

summary: discusses how to share session state between classic asp and microsoft asp.net using microsoft .net framework classes and the serialization feature of the .net framework. sharing session state allows converting existing asp applications to asp.net applications in stages while running the applications side by side. (12 printed pages)

download the source code for this article.

contents
introduction
conceptual overview
asp.net implementation
asp implementation
demo program
incorporating the com object in an existing asp application
limitation/improvement
conclusion

introduction
microsoft® asp.net is the latest microsoft technology for developing web-based applications. it offers a number of advantages over the classic asp script technology, including: 1) a better development structure by separating the ui presentation from business logic; 2) its code is fully compiled instead of interpreted as in classic asp; and 3) its compile feature in conjunction with its caching support means significantly better performance for sites written in asp.net over equivalent sites written in classic asp.

despite the potential benefit of converting existing asp applications to asp.net, many existing asp applications are mission critical and complex. the conversion process could be resource intensive and induce additional risk to the existing application. one approach to address these issues is to run the asp and asp.net side by side, and convert one section of the application at a time to asp.net. in order to run the new and old application side by side, a mechanism is needed to share the session state between classic asp and asp.net. in this article, i'll discuss how the session state can be shared by using several classes and the serialization feature of the microsoft® .net framework.

conceptual overview
cookies are the most common way for web applications to identify the user session, and can be used to identify session state for both classic asp and asp.net. session state information is stored in memory in asp script and can't be shared with other applications, such as asp.net. if the session state is stored in a common format in microsoft® sql server, the session state can be accessible by both classic asp and asp.net.

in this example, a cookie named mysession is used to identify the user session. when a user makes a request to the web application, the user will be issued a unique cookie to identify the session. on subsequent request, the browser will send the unique cookie back to the server to identify the session. before the requested web page is loaded, a custom object will reload the user session data from sql server using the unique cookie. the session state is accessible in the web page through the custom object. after the web request is finished, the session data will be persisted back to the sql server as the request terminates (see figure 1).



figure 1. sample data flow

asp.net implementation
in asp.net, every web page derives from the system.web.ui.page class. the page class aggregates an instance of the httpsession object for session data. in this example, a custom page class called sessionpage is derived from the system.web.ui.page to offer all the same features as the page class. the only difference with the derived page is that the default httpsession is overridden with a custom session object. (using the new modifier for the instance variable, c# allows the derived class to hide members of the base class.)

   public class sessionpage : system.web.ui.page
   {
      ...
      public new mysession session = null;
      ...
   }

the custom session class is responsible for storing the session state in memory using the hybriddictionary object. (hybriddictionary can efficiently handle any number of session elements.) the custom session class will limit the session data type to be string only for interoperability with the classic asp. (the default httpsession allows any type of data to be stored in the session, which will not interoperate with the classic asp.)

   [serializable]
public class mysession
   {
      private hybriddictionary dic = new hybriddictionary();

      public mysession()
      {
      }

      public string this [string name]
      {
         get
         {
            return (string)dic[name.tolower()];
         }
         set
         {
            dic[name.tolower()] = value;
         }
      }
   }

the page class exposes different events and methods for customization. in particular, the oninit method is used to set the initialize state of the page object. if the request does not have the mysession cookie, a new mysession cookie will be issued to the requester. otherwise, the session data will be retrieved from sql server using a custom data access object, sessionpersistence. the dsn and sessionexpiration values are retrieved from the web.config.

      override protected void oninit(eventargs e)
      {
         initializecomponent();
         base.oninit(e);
      }
      private void initializecomponent()
      {    
         cookie = this.request.cookies[sessionpersistence.sessionid];

         if (cookie == null)
         {
            session = new mysession();
            createnewsessioncookie();
            isnewsession = true;
         }
         else
            session = sessionpersistence.loadsession(
server.urldecode(cookie.value).tolower().trim(),
dsn,
sessionexpiration
);
            
         this.unload += new eventhandler(this.persistsession);
      }
      private void createnewsessioncookie()
      {
         cookie = new httpcookie(sessionpersistence.sessionid,
            sessionpersistence.generatekey());
         this.response.cookies.add(cookie);
      }

the sessionpersistence class uses the binaryformatter of the microsoft .net framework to serialize and deserialize the session state in binary format for optimal performance. the resulting binary session state data can then be stored in the sql server as an image field type.

      public  mysession loadsession(string key, string dsn,
                                    int sessionexpiration)
      {
         sqlconnection conn = new sqlconnection(dsn);
         sqlcommand loadcmd = new sqlcommand();
         loadcmd.commandtext = command;
         loadcmd.connection = conn;
         sqldatareader reader = null;
         mysession session = null;

         try
         {
            loadcmd.parameters.add("@id", new guid(key));
            conn.open();
            reader = loadcmd.executereader();
            if (reader.read())
            {
               datetime lastaccessed =
reader.getdatetime(1).addminutes(sessionexpiration);
               if (lastaccessed >= datetime.now)
                  session = deserialize((byte[])reader["data"]);
            }
         }
         finally
         {
            if (reader != null)
               reader.close();
            if (conn != null)
               conn.close();
         }
         
         return session;
      }
private mysession deserialize(byte[] state)
      {
         if (state == null) return null;
         
         mysession session = null;
         stream stream = null;

         try
         {
            stream = new memorystream();
            stream.write(state, 0, state.length);
            stream.position = 0;
            iformatter formatter = new binaryformatter();
            session = (mysession)formatter.deserialize(stream);
         }
         finally
         {
            if (stream != null)
               stream.close();
         }
         return session;
      }

at the end of the request, the page class unload event is fired, and an event handler registered with the unload event will serialize the session data into binary format and save the resulting binary data into sql server.

      private void persistsession(object obj, system.eventargs arg)
      {      sessionpersistence.savesession(
               server.urldecode(cookie.value).tolower().trim(),
               dsn, session, isnewsession);
      }
      public void savesession(string key, string dsn,
mysession session, bool isnewsession)
      {
         sqlconnection conn = new sqlconnection(dsn);
         sqlcommand savecmd = new sqlcommand();         
         savecmd.connection = conn;
         
         try
         {
            if (isnewsession)
               savecmd.commandtext = insertstatement;
            else
               savecmd.commandtext = updatestatement;

            savecmd.parameters.add("@id", new guid(key));
            savecmd.parameters.add("@data", serialize(session));
            savecmd.parameters.add("@lastaccessed", datetime.now.tostring());
      
            conn.open();
            savecmd.executenonquery();
         }
         finally
         {
            if (conn != null)
               conn.close();
         }
      }
private byte[] serialize(mysession session)
      {
         if (session == null) return null;

         stream stream = null;
         byte[] state = null;

         try
         {
            iformatter formatter = new binaryformatter();
            stream = new memorystream();
            formatter.serialize(stream, session);
            state = new byte[stream.length];
            stream.position = 0;
            stream.read(state, 0, (int)stream.length);
            stream.close();
         }
         finally
         {
            if (stream != null)
               stream.close();
         }
         return state;
      }

the sessionpage class and its associated classes are packaged in the sessionutility assembly. in a new asp.net project, a reference will be made to the sessionutility assembly, and every page will derive from the sessionpage instead of from the page class in order to share session with classic asp codes. once the porting is completed, the new application can switch back to use the native httpsession object by commenting out the session variable declaration in the sessionpage class to unhide the base httpsession.

最大的网站源码资源下载站,

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表