[Asp. Net] State management (Session, Application, Cache, Cookie, Viewstate, hidden domain, query string), cookieviewstate

Source: Internet
Author: User
Tags server memory

[Asp. Net] State management (Session, Application, Cache, Cookie, Viewstate, hidden domain, query string), cookieviewstate

 

 

Running result:

 

2. Session is the user variable stored on the server. I can set a value for the Session on one page and access it on another page.

The method for attaching a Session value is as follows:

2. Application

 

Explanation: If data should be shared among multiple clients, the application state can be used to save the data. The usage of application status is very similar to that of Session. For the Application status, you should use the HttpApplication class, which can be accessed through the Application attribute of the Page class.

Generally, an Application can be used to count the number of people accessing the website. When a Web Application is started, the Application variable userCount is initialized. Application_Start () is the time processing method in the global. asax file. This method is called when the first Asp. Net page of the website is started.

In the Application_Start () event handler, the value of the application variable userCount increases progressively.Before changing the Application variables, the application object must be locked using the Lock () method. Otherwise, thread problems may occur because multiple users can access one application variable at the same time. After changing the value of the application variable, you must call the Unlock () method. Note that the time for locking and unlocking is relatively short. During this period, the file orDatabase. Otherwise, other users must wait until the data access is complete.

Running result:

Note: Do not store too much data in the application state, because the application state requires server resources until the server is stopped or restarted.

3. Cache

The advantage of using the Cache class is that when the cached data changes, the Cache class will invalidate the data and re-Add the cached data, and then notify the application to report timely updates to the Cache.

1. Common Methods

Create cache
In the DotNet environmentCache. Insert (string key, object o)Method.
The key represents the cache ID, and o represents the object stored in the cache.
Add: Add data to the Cache object
Insert: Insert a data item to the Cache to modify an existing data Cache item.
Destroy cache
ProcedureCache. Remove (string key)
The key indicates the cache ID.
Call cache
Cache supports packing/unpacking. For example, you can pass a DataSet object ds throughCache. Insert ("dsCache", ds)To the Cache, You can unpack the boxDataSet ds = (DataSet) Cache ["dsCache"]To access it.
Get Data
Get: Get the specified data item from the Cache Object. Note that the returned data type is Object and type conversion is required.
GetType: gets the data item type from the Cache object. After determining the data type, the conversion is convenient.
GetEnumerator
Cyclically access the cached data items in the Cache object. Note that the return type is "IDictionaryEnumerator"
The following code demonstrates how to apply these methods to the Cache class. When using this code, you must note that the Arraylist object is used in the Code. Therefore, you must add a reference to the namespace "System. Collections" and forget to add a namespace when using the Cache category.

Tip: when using the GetType method, to determine the type, you need to use the Object. GetType (). Name attribute to obtain the type Name.

 

Running result:

When reading data of the ArrayList type, the System. Collections. ArrayList object is retrieved because no type conversion is performed.

2. When to use cache?
Cache is generally used when data is relatively fixed and frequently used. For example, you can store product information in the invoicing system into the cache, and call the cache when the user calls the product information, which greatly reduces the interaction between the user and the database, improves system performance. On the contrary, the cache is not suitable for scenarios with fast data changes and narrow application scope. For example, you can save a specific purchase order to the cache.
3. cache call considerations
The Cache has a time limit. When the expiration time set by the server is exceeded, it will be recycled by the server. When the cache is recycled, the corresponding memory block will be cleared. When you access the object through the cache ["cachekey"] Again, the return value is null. Therefore, exceptions may occur in the following calls:
4. cache Function

Typical application: implement the data cache quick reading Function

The purpose of this example is to fill the directory list in the drop-down box. When the cache fails, the contents of the directory list are blank. The demo procedure is as follows.

If you click the button within five seconds, the directory list is displayed normally. If the number of seconds is exceeded, the cached object does not exist. Therefore, the content of the drop-down list box is empty.

4. Viewstate

I. Principle of ViewState

1. the browser requests the Default. aspx page
2. when the server finds the created ViewState, it will automatically create a name named _ VIEWSTATE (the dual-downlink Slide lines are all capitalized) after base64 encryption, the value of the hidden domain is returned to the browser. This encryption process is completed in the SaveAllState method in the SaveState event of the page lifecycle.

3. When the browser submits a form, the hidden fields of _ VIEWSTATE are also submitted to the server. At this time, the ReadState event of the page lifecycle is reported.
The ReadAllState method of will decrypt the encrypted value against base64 and assign the value to the ViewState named name.
4. Finally, operate the value in ViewState.

Ii. ViewState usage:

1.Define ViewState attributes

Public intPageCount {

Get {return (int) ViewState ["PageCount"];}

Set {ViewState ["PageCount"] = value ;}

}

2.Conditions for using ViewState

To use ViewState, you must have a server form tag (<form runat = "server">) on the ASPX page ). Form fields are required so that hidden fields containing ViewState information can be returned to the server. In addition, this form must also be a form on the server side. When this page is executed on the server, the ASP.net page framework can add hidden fields.

The value of EnableViewState in page is true.

The value of the EnableViewState attribute of the control is true.

Iv. Comparison between viewstate and session

(1) If the session value is stored in the server memory, it is certain that a large number of sessions will increase the server load. viewstate stores data in the page hidden control and no longer occupies server resources. Therefore, we can save some variables and objects that need to be remembered by the server to viewstate. the session should only be applied to variables and object storage that need to span pages and are related to each access user.

(2) The session will expire in 20 minutes by default, while the viewstate will never expire.

However, viewstate does not store all. net data. It only supports String, Integer, Boolean, Array, ArrayList, Hashtable, and custom data types.

Everything has two sides. Using viewstate will increase the html output of the page and occupy more bandwidth, which requires careful consideration. in addition, because all viewstates are stored in a hidden field, you can easily view the base64 encoded value by viewing the source code. after conversion, you can get the objects and variable values in your storage.

5. Cookie
It is used to save the request information of the client browser request server page. The validity period can be set manually, and the data size stored is very limited. Therefore, do not save datasets and other large amounts of data. Moreover, cookies store data in plain text on the client's computer, so it is best not to store sensitive unencrypted data.

The following are cookie methods:

6.Hide domain


A hidden domain is a special space in a webpage that is not displayed on the webpage. It is mainly used to store data that does not need to be displayed on the webpage during webpage interaction.
Hidden domains are invisible elements used to collect or send information. For webpage visitors, hidden domains are invisible. When a form is submitted, the hidden field will send the information to the server with the name and value you set.
Example: <input type = "hidden" name = "ExPws" value = "dd">
To put it bluntly, the hidden domain is not visible at the front end, just like the elements in the form. There is a value in the name, but the data being submitted is invisible.

Example: InASPThe hidden fields can be used to hide forms, so that the input box can be displayed on the webpage without the restrictions of the form.
<Input name = "id" type = "hidden" value = "abc">
<% = "The Hidden Domain value is:" & request ("id") %>

This form is displayed after it is submitted.

The hidden Domain value is abc.

7. query strings

When the server executes the Response. Redirect statement, the lifecycle of the page is immediately interrupted and information is directly returned to the client for redirection.

ASP. NETThere are three methods for server-side redirection

1. Server. Transfer ("xxx. aspx "):

The server stops parsing this page, saves the data on this page before turning, redirects the page to newPage. aspx, and returns the result of adding the newPage. aspx page to the browser.

2. Server. Execute ("xxx. aspx ");

After the server saves this page to the previous data, It redirects the page to newPage. aspx for execution, returns this page for execution, merges the three results, and returns them to the browser.

3. Response. Redirect ("xxx. aspx "):

When the server executes this method, it sends a message to the client browser, asking the client browser to send a new http request. The request url is "xxx. aspx ". The browser then transfers the new http request to the xxx. aspx page.

Summary:

1. Storage of user variables: Common sessions

2. Page jump: query strings are commonly used.

3. Cache

L cookie (used to save the request information of the client browser's request Server Page. Its validity period can be set manually, and the data volume stored is very limited)

L cache (used for data cache update)

L viewstate (stored in a hidden domain, which does not occupy service resources and will never expire, but will increase html output and occupy bandwidth)

L application (applicable to the entire application, which is equivalent to a global variable, but is not very widely used and can be used to count the number of people)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.