[ASP] state management (Session, Application, Cache, Cookie, Viewstate, hidden field, query string)

Source: Internet
Author: User

    1. Session:
      1. The session begins when the customer opens the ASP. NET page for the first time on the server. When the client does not have access to the server within 20 minutes, the session ends and the sessions are destroyed. (You can also set the cache time in Web. config) You can initialize session variables in the global.aspx session_start () event handler. In the following instance, the session state named MyData is initialized to 0:

Operation Result:

2.Session is a user variable that is saved on the server side. I can value the session in one page and then access it on another page.

The value of the session is as follows:

2.Application

Explanation: If your data should be shared across multiple clients, you can use application state to save it. Application state is used in a very similar way to the session. For application state, you should use the HttpApplication class, which is accessible through the Application property of the page class.

Typically application can be used to count the number of visitors to a Web site, initializing the application variable UserCount when launching a Web application. Application_Start () is a time-handler method in the Global.asax file that is called when the first ASP. NET page of a Web site is started.

In the Application_Start () event handler, the value of the application variable UserCount is incremented. before changing the application variable, the Application object must be locked with the lock () method, or a threading problem occurs because multiple users can access an application variable at the same time. After changing the value of the application variable, you must also call the Unlock () method. Note Locking and unlocking time is relatively short, and in this time period, the data in the file or database should not be read . Otherwise, other users must wait until data access is complete before they can operate.

Operation Result:

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

3.Cache

The advantage of using the cache class is that when the cached data changes, the cache class invalidates the data, implements the re-addition of the cached data, notifies the application, and reports the cache's timely updates.

1. Common methods

Create cache
Created by the Cache.Insert (String key,object O) method in a dotnet environment.
Where key means the id,o of the cache represents the object stored in the cache.
Add: Adding data to the cache object
Insert: Inserts a data item into the cache that can be used to modify a data cache entry that already exists
Destroy Cache
by Method Cache.remove (string key)
Where key represents the ID of the cache.
Call the Cache
The cache supports boxing/unpacking operations. If you can save a DataSet object DS to the Cache via cache.insert ("Dscache", DS) , you can do this by unpacking the DataSet ds = (DataSet) cache[" Dscache "] to access it.
Get Data
Get: Gets the specified data item from the cache object, noting that the object type is returned and that a type conversion is required
GetType: Gets the type of data item from the cache object, determines the data type, and facilitates the conversion
GetEnumerator
Iterates through the cache data items in the cache object. Note that its return type is "IDictionaryEnumerator"
The following code demonstrates how to apply these methods of the cache class. When using this code, be aware that the ArrayList object is used in your code, so you need to add a reference to the namespace "System.Collections" and forget to add a namespace using the cache category

Tip: When using the GetType method, if you want to determine the type, you need to use Object.GetType (). The Name property gets the names of the types.

Operation Result:

When reading data of type ArrayList, the object with type "System.Collections.ArrayList" is removed because there is no type conversion.

2. When to use the cache
Caches are typically used in more frequent places where data is more fixed. For example, the invoicing system can be stored in the product information cache, the user calls the product information by the cache can be called, which greatly reduces the user's interaction with the database, improve the performance of the system. On the other hand, thecache is not suitable for use in areas where data changes quickly and in a narrow range . For example, a specific purchase order is credited to the cache.
3.cache Call Considerations
There is a time limit for the cache. When the server setting expires, it is recycled by the server. When the cache is reclaimed, the corresponding memory block is emptied, and the null value is returned when the object is accessed again by cache["CacheKey". So the following call will be an exception
4. Caching function

Typical application: Cache fast read function for data

The purpose of this example is to populate the list of directories into a drop-down box, and when the cache is invalidated, the contents of the directory list are empty. The steps to demonstrate are described below.

Within 5 seconds if the button is clicked, the directory list is displayed normally, and if more than 5 seconds, the cached object no longer exists, so the contents of the drop-down list box are empty.

4. Viewstate

First, the principle of ViewState

1. Browser Request Default.aspx page
2. VIEWSTATE created at server-side discovery This time automatically creates a hidden field named __viewstate (double-dip All caps) The value of its hidden field is base64 encrypted and returned to the browser side this encryption process is done in the Saveallstate method in the SaveState event of the page life cycle

3. When the browser submits the form, the __viewstate hidden field is also submitted to the server at this time, the ReadState event of the page life cycle
The Readallstate method decrypts the encrypted value back to Base64 and finally assigns the value to the viewstate named name.
4. Finally, to manipulate the values in the ViewState

Second, the use of ViewState:

1. defining ViewState Properties

Public intpagecount{

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

set{viewstate["PageCount"]=value;}

}

2. conditions for using ViewState

If you want to use ViewState, you must have a server-side form tag in the ASPX page (<form runat = "server" >). A form field is required so that a hidden field containing viewstate information can be passed back to the server. Also, the form must be a server-side form, so that the ASP. NET page framework can add hidden fields when the page is executed on the server.

The EnableViewState property value of page is True

The EnableViewState property value of the control is true

Iv. comparison of ViewState and session

(1) The session value is stored in the server memory, then, it is certain that a large number of use of the session will result in heavier server burden. Instead of ViewState server resources by simply depositing data into a page-hidden control, we can save variables and objects that require the server to "remember" into viewstate. The session should only be used on variables and object stores that need to cross pages and are related to each access user.

(2) The session expires in 20 minutes by default, and ViewState never expires.

But ViewState is not able to store all of the. NET type data, it only supports string, Integer, Boolean, Array, ArrayList, Hashtable, and some types of customizations.

Everything has two sides, using ViewState will increase the output of the page HTML, occupy more bandwidth, which we need to consider carefully. In addition, since all viewstate are stored in a hidden domain, the user can easily view the source code to see this base64 encoded value. Then you can get the object and the variable value that you stored in the conversion.

5. Cookies
The request information that is used to save the client browser Request Server page, its validity period can be set artificially, and the amount of data stored is very limited, so do not save the dataset and other large amounts of data. And the cookie stores the data information in plaintext in the client's computer, so it is best not to save sensitive unencrypted data.

Here are a few ways to Cookie:

6. hidden Fields


A hidden field is a special space within a Web page that is not displayed in a Web page and is used primarily to store data that does not need to be displayed on a Web page when interacting with a Web page.
Hidden fields are invisible elements that are used to collect or send information, and hidden fields are invisible to visitors to a Web page. When a form is submitted, the hidden field sends the information to the server with the name and value that you defined when you set it.
Example:
In fact, the hidden domain is not visible in the foreground, as the elements of the form. There is a value for the name, but the submission of the data is invisible.

Example: in ASP hidden fields can be used for hidden forms so that the input box can be arbitrarily laid out on a Web page without the restrictions of the form
<input name= "id" type= "hidden" value= "abc" >
<%= "Hidden Domain value:" & Request ("id")%>

When this form is submitted, it will be displayed

Hidden field values are: ABC

7. Query string

When the server executes to the Response.Redirect statement, the life cycle of the page is immediately interrupted, and information is returned directly to the client, allowing the client to redirect the operation.

ASP , there are three methods of server end multiplicity orientation

1.server.transfer ("xxx.aspx"):

The server stops parsing this page, saves the data before turning it, and then turns the page to newpage.aspx and returns the Newpage.aspx page results to the browser.

2.server.execute ("xxx.aspx");

After the server saves this page to the previous data, it turns the page to newpage.aspx execution, and then returns to this page to continue execution. Merge the three results back to the browser.

3.response.redirect ("xxx.aspx"):

When the server executes to this method, it sends the message to the client browser to send a new HTTP request to the client browser, which has a URL of "xxx.aspx". The browser then goes to the Xxx.aspx page with a new HTTP request.

Summarize:

1. Storage of User variables: session more commonly used

2. Page Jump: query string comparison common

3. Caching

L cookie (used to save request information of client browser Request Server page, its validity period can be set artificially, and the amount of data stored is very limited)

L Cache (for data cache updates)

L viewstate (stored in a hidden domain, does not occupy service resources, never expires but increases the amount of HTML output, consumes bandwidth)

L Application (applies to the entire application, equivalent to global variables, but is not very useful and can be used for counting people)

[ASP] state management (Session, Application, Cache, Cookie, Viewstate, hidden field, query string)

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.