Session State

A Session State Example

 

 public class Furniture 


     public  string Name; 
     public  string Description; 
     public  decimal Cost; 
 
     public Furniture( string name,  string description, 
       decimal cost) 
    { 
        Name = name; 
        Description = description; 
        Cost = cost; 
    } 
}

 

public  partial  class SessionStateExample : System.Web.UI.Page 

     protected  void Page_Load(Object sender, EventArgs e) 
    { 
         if (! this.IsPostBack) 
        { 
             //  Create Furniture objects. 
            Furniture piece1 =  new Furniture( " Econo Sofa "
                                         " Acme Inc. "74.99M); 
            Furniture piece2 =  new Furniture( " Pioneer Table "
 
                                         " Heritage Unit "866.75M); 
            Furniture piece3 =  new Furniture( " Retro Cabinet "
                                         " Sixties Ltd. "300.11M); 
 
             //  Add objects to session state. 
            Session[ " Furniture1 "] = piece1; 
            Session[ " Furniture2 "] = piece2; 
            Session[ " Furniture3 "] = piece3; 
 
             //  Add rows to list control. 
            lstItems.Items.Add(piece1.Name); 
            lstItems.Items.Add(piece2.Name); 
            lstItems.Items.Add(piece3.Name); 
        } 
 
         //  Display some basic information about the session. 
        
//  This is useful for testing configuration settings. 
        lblSession.Text =  " Session ID:  " + Session.SessionID; 
        lblSession.Text +=  " <br />Number of Objects:  "
        lblSession.Text += Session.Count.ToString(); 
        lblSession.Text +=  " <br />Mode:  " + Session.Mode.ToString(); 
        lblSession.Text +=  " <br />Is Cookieless:  "
        lblSession.Text += Session.IsCookieless.ToString(); 
        lblSession.Text +=  " <br />Is New:  "
        lblSession.Text += Session.IsNewSession.ToString(); 
        lblSession.Text +=  " <br />Timeout (minutes):  "
        lblSession.Text += Session.Timeout.ToString(); 
    } 
 
     protected  void cmdMoreInfo_Click(Object sender, EventArgs e) 
    { 
         if (lstItems.SelectedIndex == - 1
        { 
            lblRecord.Text =  " No item selected. "
        } 
         else 
        { 
             //  Construct the right key name based on the index. 
             string key =  " Furniture " + 
                  (lstItems.SelectedIndex +  1).ToString(); 
 
             //  Retrieve the Furniture object from session state. 
            Furniture piece = (Furniture)Session[key]; 
 
             //  Display the information for this object. 
            lblRecord.Text =  " Name:  " + piece.Name; 
            lblRecord.Text +=  " <br />Manufacturer:  "
            lblRecord.Text +=  piece.Description; 
            lblRecord.Text +=  " <br />Cost:  " + piece.Cost.ToString( " c "); 
        } 
    } 

}  

 

 Session State Configuration

 

 The following listing shows the most important op tions that you can set for the <sessionState> 

element. Keep in mind that you won’ t use all of these details at the same time. Some settings apply only to certain session state  modes, as you’ll see shortly. 

 

 <?xml version="1.0" ?> 

< configuration > 
     < system.web > 
         <!--  Other settings omitted.  --> 
 
         < sessionState 
            
cookieless ="UseCookies"  
            cookieName
="ASP.NET_SessionId"  
            regenerateExpiredSessionId
="false"  
            timeout
="20"  
            mode
="InProc"  
            stateConnectionString
="tcpip=127.0.0.1:42424"  
            stateNetworkTimeout
="10"  
            sqlConnectionString
="data source=127.0.0.1;Integrated Security=SSPI"  
    sqlCommandTimeout
="30"
            allowCustomSqlDatabase
="false"
            customProvider
=""
            compressionEnabled
="false"
        />
    </ system.web >
</ configuration >

 

 Mode

InProc 

InProc is the default mode, and it makes the most sense for small websites. 


Off 
This setting disables session state management for every page in the application. This can provide a slight performance improvement for websit es that are not using session state.  

 

StateServer 

With this setting, ASP.NET will use a separate Windows service for state management. This service runs on the same web server, but it’s outside the main ASP.NET process, which gives it a basic level of protection if the ASP.NET process needs to be restarte d. The cost is the increased time delay imposed when state information is transferred between two processes. If you frequently access and change state information, this can make for a fairly unwelcome slowdown. 
When using the StateServer setting, you need to specify a value for the stateConnectionString setting. This string identifies the TCP/IP address of the computer that is running the StateServer service and its port number (which is defined by ASP.NET and doesn’t usually n eed to be changed). This allows you to host the StateServer on another computer. If you don’t change this setting, the local server will be used (set as address 127.0.0.1). 

 

SQLServer 
This setting instructs ASP.NET to use an SQL Server da tabase to store session information, as identified by the sqlConnectionString attribute. This is the most re silient state store but also the slowest by far. To use this method of state management, you’ll need to have a server with SQL  Server installed. 
When setting the sqlConnectionString attribute, you follow the same sort of pattern you use with ADO.NET data access. Generally, you’ll need to specify a data source (the server address) and a user ID and password, unless you’re using SQL integrated security.  

 

 Here’s a command that creates the session storage database on the current computer, using the default database name ASPState: 

aspnet_regsql.exe -S localhost -E –ssadd

 

  < sessionState  mode ="SQLServer"  
 sqlConnectionString
="data source=127.0.0.1;Integrated Security=SSPI"  
 ... 
/> 

 

Custom 

When using custom mode, you need to indicate which session state store provider to use by supplying the customProvider attribute.

 

Compression 

When you set enableCompression to true, session data is compressed before it’s passed out of process. The enableCompression setting only has an effect  when you’re using out-of-process session state storage, because it’s only in this situation that the data is serialized. 

 

 

Application State 

Application state allows you to store global objects that can be accessed by any client. Application state is based on the System.Web.HttpApplicationState class,  which is provided in all web pages through the built-in Application object. 
Application state is similar to session state. It supports the same type of objects, retains information on the server, and uses the same dictionary-based syntax. A common example with application state is  a global counter that tracks how many times an operation has been performed by all the web application’s clients. 
For example, you could create a global.asax event ha ndler that tracks how many sessions have been created or how many requests have been received into  the application. Or you can use similar logic in the Page.Load event handler to track how many times a given page has been requested by various clients. Here’s an example of the latter: 
protected  void Page_Load(Object sender, EventArgs e) 

     //  Retrieve the current counter value. 
     int count =  0
     if (Application[ " HitCounterForOrderPage "] !=  null
    { 
        count = ( int)Application[ " HitCounterForOrderPage "]; 
    } 
 
     //  Increment the counter. 
    count++; 
 
     //  Store the current counter value. 
    Application[ " HitCounterForOrderPage "] = count; 
    lblCounter.Text = count.ToString(); 

 Application state isn’t often used, because it’s gen erally inefficient. In the previous example, the counter would probably not keep an accurate count, partic ularly in times of heavy traffic. 

 To prevent this problem, you need to use the Lo ck() and Unlock() methods, which explicitly allow only one client to access the Application state collection at a time. 


 To prevent this problem, you need to use the Lo ck() and Unlock() methods, which explicitly allow only 

one client to access the Application state collection at a time. 
protected  void Page_Load(Object sender, EventArgs e) 

     //  Acquire exclusive access. 
    Application.Lock(); 
 
     int count =  0
     if (Application[ " HitCounterForOrderPage "] !=  null
    { 
        count = ( int)Application[ " HitCounterForOrderPage "]; 
    } 
    count++; 
    Application[ " HitCounterForOrderPage "]=count;
     // Releaseexclusiveaccess.
    Application.Unlock();
    lblCounter.Text=count.ToString();
}

 

 

 

转载于:https://www.cnblogs.com/JasonBie/archive/2012/04/12/2444260.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值