ASP.NET maintains nine selection of user status

xiaoxiao2021-03-06  115

2003-06-10

■ Tao Gang compile

■ Yesky

Summary: ASP.NET provides a variety of different ways to maintain data between user requests. You can use Application objects, cookie, hidden fields, sessions, or cache objects, as well as a lot of methods. Decide when to use them sometimes difficult. This article will introduce the above techniques and give some guidance when using them. Although some of these technologies have existed in traditional ASPs, when there is a .NET framework assembly, when they use them to change. In order to maintain data in ASP.NET, you need to adjust the knowledge learned from the previous ASP.

With the arrival of the Web era, the management status in the state of incorrect HTTP is a big problem for web developers. There are recent different technologies that store and retrieve data. This article I will explain how the ASP.NET developer can maintain or transfer status through the page request.

In ASP.NET, there are several ways to maintain data between users - actually too much, so that no experience is very confused to use which object in which particular environment is very confused. In order to answer this question, we need to consider the following three conditions:

Who needs data?

How long is the data need to be maintained?

How big is the data set?

By answering these questions, you can decide which object provides the best solution to keep the ASP.NET application request interval. Figure 1 lists different status management objects and describes when using them. ASP.NET adds four new objects: cache, context, viewstate, and web.config files. ASP.NET also supports traditional ASP objects, including Application, cookie, Form Post, QueryString, and Sessions with hidden fields. Note that the correct usage of these five data containers has changed, so experienced programmers may need to learn some knowledge when considering these familiar objects.

Keeping Method Who wants to maintain how long the amount of data size Application All users The entire application life Date can be very short, and if the user does not delete it, you can very small, simple data Form Post A user to the next request (You can repeatedly span multiple requests) Any size queryString one or a group of users to the next request (can be used across multiple requests) Small, simple data sessions, a user's user activity, maintained a period of time (general 20 minutes) ) Can be any size, but because the user has a separate sessions storage, all it should be minimal. Cache All users or some users can be large as needed, simple and complicated Context A user can keep a large object, but it is generally not like this to use ViewState a web form minimum config file knows that the configuration file is updated. You can maintain a lot of data, usually tissue small strings and XML structures

Table 1. Data container objects in ASP.NET

Application

Let us explain the object by answering the status of the above status problem. Who needs data? All users need to access it. How long does it take to keep your data? Keep permanently or remain in the application survival. How big is the data? Can be any size - only a copy of the data at any given time exists.

In traditional ASP, the Application object provides a location that saves frequently used but few variables, such as menus content and reference data. Although Application in ASP.NET still exists as a data container, there are other objects of data in the Application collection of the traditional ASP application before.

In the traditional ASP, if the saved data is not changed at all in the application's life (or few changes, such as read-only data and most cases are read operations), Application objects are ideal. The connection string is the most common data sheet saved in the Application variable, but similar configuration data in ASP.NET is best saved in the web.config file. If you use the Application object, a question that needs to be considered is any write operation either in the Application_OnStart event (Global.asax) or in the Application.lock section. Although using Application.lock to ensure that the write operation is implemented correctly, it serves serving a request for Application objects, and this is a serious performance bottleneck for the application. Figure 2 demonstrates how to use Application objects, which includes a web form and its code file. Application.aspx

set application variable:
name *
value *
FORMAPPLICATION.ASPX.CSPRIVATE VOID BTNSUBMIT_CLICK (Object Sender, System.EventArgs E) {if (isvalid) {Application.loc K (); Application [txtname.text] = txtValue.text; Application.Unlock (); lblresult.text = "The value of " txtname.text "

In The Application Object Is Application [TXTName.Text] .tostring () "";}} code segment 1. Access Application object in ASP.NET

Its output is shown below:

Figure 1. Content of the Application object

Note that the contents of the Application object in Figure 3 are the display of the tracking output. Tracking is a great debugging tool, but at a point, the trackable page that is opened may appear in the product environment. If this happens, you don't want to display sensitive information. That is why the Application object never is a primary reason for the location of the recommended storage sensitive information (such as the connection string).

Cookies

Cookies are very convenient when a specific user needs a specific data sheet and needs to be kept in a variable time period. Its life cycle may be as short as the browser form, or months, for several years. Cookies can be smaller to only a few bytes because they pass through each browser request, and their content needs to be as small as possible.

Cookie offers a flexible, powerful maintenance user request between data, which is why most dynamic sites on the Internet use their reasons. Because cookie can store the amount of data is limited, it is best to save the key field in cookie, and other data is saved in a database or other server-side data container. However, because all browsers are not supported, they can be disabled or deleted by the user, so they cannot be used to save critical data. You should have a good way to delete the user's cookie. Finally, cookie is saved in a user's computer as a simple plain text, so it cannot save sensitive, unprinted data inside it.

Figure 2. Single value and multi-value cookie

There is a special cookie to save a single value or a collection of names / values. Figure 4 shows an example of a single and multiple values ​​cookies, and outputs the built-in tracking feature of ASP.NET. These values ​​can be maintained using the request.cookies and response.cookies collection in the ASP.NET page, which is demonstrated in the code segment 2.

Cookies.aspx.cs

// Use HttpCookie category refers cookie value and / or sub-values ​​HttpCookie cookie; if (Request.Cookies [txtName.Text] == ​​null) cookie = new HttpCookie (txtName.Text, txtValue.Text); elsecookie = Request. cookies [txtName.Text]; if (txtSubValueName.Text.Length> 0) cookie.Values.Add (txtSubValueName.Text, txtSubValueValue.Text); cookie.Expires = System.DateTime.Now.AddDays (1); // tomorrowResponse .Appendcookie (cookie); // Retrieve the value of cookie if (! Request.cookies [txtname.text] .HASKEYS) lblresult.text = "The value of the " txtname.text " cookie IS " Request.cookies [txtname.text] .Value.tostring () " "; else {lblResult.text =" The value of the txtname.text "< / b> cookie is " Request.cookies [txtname.text] .value.toTString () " ";} Deleting a cookie // The value set is empty and set the termination time to response.cookies [txtname.text] .value = null; response.cookies [txtname.text] .Expires = system.datetime.now.addmonths (-1); // Last month code segment 2.accessing Access to cookies in ASP.NET

Form Post / Hidden Forms

The specific user needs the data of the form, and it needs to be held at any stage of a single request to the application. These data can actually be arbitrary, which transmits forward and backward as each Form POST is forwarded backwards.

In traditional ASP, this is a usual way to expose the state in the application, especially in multi-page form applications. But in ASP.NET, this technology is not suitable because as long as you use the Postback model (that is, the page is sent back to yourself), the web control and viewState automatically processes these operations. ViewState is an ASP.NET implementation of this technology, I will discuss it in the following part of this article. Accessing the form value sent through the POST is done using the form set using the HttpRequest object. In Figure 6, an ASP.NET page sets an ID of a user, which is held in a hidden form field. The request to any page is retained until the page is linked to another user using the Submit button. Form1.aspx

form 1

Your username: < / p>

Set Hidden Form Username Variable: * < / TD>
< / TR> Form1.aspx.csprivate void page_load (Object Sender, SYST EM.Eventargs e) {if (! ispostback) // New request or request from Form2.aspx {// Check Form Set IF (Request.form ["UserName"] ==

NULL) PNLSetValue.visible = true; else {// Need to set the user name value PNLSetValue.visible = false; username = request.form ["username"]. Tostring (); lblusername.text = username; // data binding to Hidden form field value this.database.database ();}} private void btnsubmit_click (object sender, system.eventargs e) {if (isvalid) {// hide form to set value PNLSetValue.visible = false; username = txtname .Text; lblresult.text = "Username set to" txtname.text "."; Lblusername.text = username; this.Database ();}} form2.aspx

form 2

Your username: form2.aspx.csprivate void page_load (object sender, system.eventargs e) {if (Request.form ["UserName"]! = null) {username = Request.form ["username"]. TOSTRING (); lblusername.text = username; this.database ();}}

Code section 3. Use hidden form fields in ASP.NET

On only one page in ASP.NET, there can be only one server-side form, and the form must be submitted to return itself (still using the client form, no limit). The hidden form field has no one of the main reasons for delivery between applications served between .NET Framework components is .NET Framework component controls You can automatically maintain your own status using ViewState. ViewState simply puts the work package contained in the use of hidden form fields and retrieves values ​​into a simple set object.

QueryString

The data saved in the QueryString object is used by a separate user. Its life cycle may have only one request as short, or there may be as long as the user uses the application (if constructed correctly). This type of data is generally less than 1 kB. The data in queryString is passed in the URL. It is visible for the user, so you can guess that when using this technique, sensitive data or data that can be used to control the application needs to be encrypted.

That is, querystring is a good way to send information between the ASP.NET Web form. For example, if there is a DataGrid containing a product list, and there is a link-oriented product on the table, using queryString is ideal, you can include the product's ID in QueryString in the product detail page ( For example, ProductDetails.aspx? Id = 4). Another benefit of using querystrings is that the state of the page is included in the URL. This means that users can put a form created by querystrings into his favorites. When they return to the page as a collection, they will be the same as the collection. Obviously this has a role when the page does not depend on querystring and there is a function when doing any changes. Sensitive data, and any variables that do not want the user to operate should be avoided here (unless encrypted makes the user can't read). And the illegal characters in the URL must be encoded using the server.urlencode, as shown in Figure 7. When processed a single ASP.NET page, viewstate is better than querystring for maintenance status. For long-term data storage, cookie, sessions, or cache is more suitable than querystrings as a data container.

QueryString.aspx

set querystring variable:
name *
value *
set querystring x equal to 1 querystring.aspx.csprivate void Page_load (Object) T Sender, System.EventArgs E) {// Retrieve the value of cookie if (Request.QueryString.hasKeys ()) {lblResult.text = "The value.text TXTNAME.TEXT

" querystring parameter is:
"; Foreach (String Key in Request.QueryString.keys) {lblResult.text = "[" Key "=" Request.QueryString [key] .tostring ( "]
";}}}} private void btnsubmit_click (object sender, system.eventargs e) {if (isvalid) {string url = "queryString.aspx?"; string key in request.queryString.Keys ) {url = key "=" Request.QueryString [key] .tostring () "&";} response.redirect (url txtname.text "=" server.urlencode (txtvalue.text)) }}

Code Segment 4. Use querystrings to pass data in ASP.NET

Sessions

Sessions data is specific for specific users. Its survival period is the time of the user's continuous request, and it is later (generally 20 minutes). Sessions can remain or large or small, but if the application is used for hundreds of users, the total storage should remain minimal.

Unfortunately, in the traditional ASP's reputation is very bad because it constrains the application to a specific computer, hinders scalability of the user packet and web. There is almost no such problem in ASP.NET because it is simple to change the location of Sessions. By default (the best performance), the sessions data is still saved in the memory of the local web server, but ASP.NET supports the use of external status server or database management sessions data.

Using the sessions object is simple, and its syntax is the same as traditional ASP. However, the Sessions object is a kind of efficiency in the method of saving user data, because even if the user stops using the application, it remains in memory for a while. This has a serious impact on the scalability of very busy sites. Other selection allows for more controls to release memory, such as Cache objects, may be more suitable for large amounts of large data values. And by default, ASP.NET sessionss depends on cookie, so if the user is forbidden or does not support cookie, Sessionss cannot work, but it can be configured to configure the sessionss support cookie. For small amounts of data, the sessionss object is a great location that holds only specific data that only needs to be held in the user's current dialog. The following example demonstrates how to set up and retrieve values ​​from the sessionss object:

Private void btnsubmit_click (object sender, system.eventargs e) {if (isvalid) {// set sessions value sessions [txtname.text] = txtValue.text;

// read and display the setup lblresult.text = "The value of txtname.text " in the sessions object is " sessions [txtname.text] .tostring "";}} The web form is almost the same as the Application object, and the contents of the sessions collection are also visible when the page tracking is allowed. What you need to remember is that even if you are not used, Sessionss will have application overhead. Setting the SessionSS status to read-only or optimizing only page that only needs to be read without writing data. You can use one of the following two ways to configure sessionss:

<% @ Page enablesState = "false"%> <% @ page enablessionsSstate = "readonly"%>

ASP.NET sessionss can be configured in the sessionsstate element in Web.config or Machine.config. Here is an example of settings in web.config:

New state container in ASP.NET

As mentioned earlier, ASP.NET has added several new ways to save the data between the user request. These pathways give you how to keep status information better control. The scope of these technologies can be narrow to only one request is so small (Context object), or it can be wide to all applications on the entire web server and server (Machine.Config file). In most cases you have a variety of choices to save a specific data - using the issues and answers described for each method to determine if an object is suitable for you.

Cache

Cache objects are used for a single user, a group of users, or all users. This data is maintained for multiple requests. It can be maintained long, but cannot exceed the time of the application restart, and the termination of the data is based on time or other dependencies. It maintains high or small amounts of data efficiently.

Cache is one of the most "cool" objects in ASP.NET. It provides an incredible flexibility, versatility, and performance, so it is usually more important than Application or Sessions in an ASP.NET application. This article does not detail the method of use of Cache objects, but it can still be said that it is an energy object. Similar to other set objects, it is a simple name-value collection, but the value of a particular user can be cached by using the key value of specifying a specific user. Also you can cache multiple data sets of different related data, such as several key (such as FordCars, Chevycars, Gmcars). Data in Cache can give an absolute, variable or file-based termination time. They also enable a callback function that is called when the cached value is extracted from the cache, this feature is useful, because then you can check if it is the latest data variable, if not (or the data source is not available), Re-cache the termination value.

The syntax of the added and access to the cache is similar to the previously mentioned. However, Cache has complemented the standard indexer method of access collection content, which supports multiple methods, allowing more control of the cached data. The most frequently used method is INSERT, which supports several overloads, allowing you to specify dependencies, timeout, priority, and callbacks. Here are some simple examples:

// Add items to the cache ["mykey"] = myValue; // Read the item from the cache Response.write (Cache ["MyKey"]);

// Add Cachedure to 10 seconds and add items to cache.insert ("mykey", myvalue, null, system.datetime.now.dseconds (10), system.Web.caching.cache.noslidingExpiration;

One of the most powerful features of the Cache object is the ability to perform a callback when an item in the cache is terminated. It uses a delegate or function pointer, which is not discussed herein. Fortunately, once you have some examples of these technologies, you can use them to use them in applications through simple shear and paste, and don't need to know how the commission is working. There are many reasons for using this feature, the most common thing to re-fill the cache with the current data when data termination, or restore the old cache data when re-filled the cache.

In my example, it simply caches the current time. When the cache is over, I will add an asterisk (*) to the string of the string in the cache. After more than time, you can determine how many times the cache is over-term by calculating the quantity of the asterisk. Figure 9 demonstrates an important concept of a callback and provides a good template for establishing more function callback programs using the cache.

Private void page_load (object sender, system.eventargs e) {string cachekey = "mykey"; string data = ""; // check if the data has been cached IF (cachekey == null) {// because of data In the cache, all read data DATA = system.datetime.now.toSTRING ();

// Establish an instance of a callback commission CacheItemRemovedCallback Callback = New CacheItemRemovedCallback (onremove);

Label1.text = "generated:" DATA;

Cache.Insert (cacheKey, data, null, System.DateTime.Now.AddSeconds (5), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, callBack);} else {Label1.Text = "Cached:" cache [cachekey] .tostring ();}}

private void onRemove (string key, object val, CacheItemRemovedReason reason) {// establish a callback delegate instance CacheItemRemovedCallback callBack = new CacheItemRemovedCallback (onRemove); Cache.Insert (key, val.ToString () "*", null, System .Datetime.now.addseconds (5), cache.nosliding.cachen, system.web.caching.cacheitempriority.default, callback;

Code section 5. Cache callback example

Note that an important feature in the code segment is to use the mode in Page_Load to determine if the data in the cache is used. This mode may also be used when you process the items in the cache. Use the IF statement to check if the current content of the cache is empty (because a reference is used multiple references, using a variable for the cache key). If it is empty, generate data from the data source and put it in the cache. If not empty, return data from the cache. If the data access logic is complex, you need to put the entire IF statement into a separate function, the task of the function is to retrieve data. The function of the Cache object is much more than most of the object we discussed. This is also one of the more powerful features of ASP.NET, and I clearly recommend reading about it. Context

The Context object holds a single user, a single request data, and the data is only held during the request. The Context container can maintain a large amount of data, but typically store small data sheets because it often implements each request in Global.asax.

The Context container (access or using system.Web.htttpContext.current) is provided to maintain values ​​that need to be passed between different httpmodules and httphandlers. It can also be used to maintain the corresponding information of a complete request. For example, the iBuysPY entry fills the container in the process of the Application_BeginRequest event in Global.asax. Note that this is only available in the current request, if you want to use it in the next request, consider using ViewState.

The syntax used to set and get data from the Context collection is similar to the other collection objects (such as Application, Sessions, and Cache) discussed. Here are two simple examples:

// Add items to Context.Items ["mykey"] = myValue;

// Read the item from Context Response.write (Context ["MyKey"]);

ViewState

ViewState keeps status information for a single user, keeping the ASPX page working hours. The ViewState container maintains a lot of data, but must be careful to manage the size of ViewState because it adds the download (Download) size for each request and response.

ViewState is a new container in ASP.NET, maybe you have used it, but you may still don't know it. This is because all built-in web controls use ViewState to keep their own values ​​between pages retrace (Postback). But you have to be careful because it affects the performance of the application. The size of the impact relies on the use of ViewState between the farten - the number of most web forms is very small.

Determine the simpler method for each control on a page, the simpler method is to open the page tracking and check how many ViewState loaded for each control. If a particular control does not need to maintain data between the firing, close the enableViewState Set to false ViewState. You can also determine a total of a given ASP.NET page viewState by checking html sources viewed in your browser. Note that these contents are encoded using Base64 to place accidental viewing and maintenance. ViewState can also be disabled through the entire page by adding enableViewState = "false" to @PAGE instructions.

Typical web forms don't need to be directly maintained for ViewState. But if you build a custom web control, you need to know how it works and implements it for your control, so that the control works in the same manner as the web control released as ASP.NET. Read or write values ​​to ViewState can be completed by the syntax of other collection objects above: // gives ViewState Add Item ViewState ["MyKey"] = MyValue;

/ / From Context Reading RESPONSE.WRITE (ViewState ["MyKey"]);

When you create a custom web control, you may want them to have the benefits of ViewState. This can be simply implemented in the attribute layer of the control. The code segment 6 demonstrates how to save a simple custom control to the person attribute to ViewState and use it in the render method of the control.

Namespace MSDN.StateManagement {public class helloperson: system.Web.ui.control {public string personname {get {string s = (string) ViewState ["Personname"]; RETURN ((s == null) "": s) } Set {ViewState ["Personname"] = value;}} protected override void render ("hello" personname);}}}

Code segment 6. Save data in ViewState

Web.config and Machine.config files

The data in these files can be used for all users of an application. The data stored in the web.config file can be used for the entire life cycle of the application. These data are generally small, which is typically used to keep the file location and a database connection. The large data sheet is preferably saved in other locations.

As a supplement to other diverse set objects, ASP.NET introduces a set of XML configuration files for managing applications even more settings for the entire server. Each ASP.NET application uses the web.config file to set a lot of properties, each server has a Machine.config file under the system folder. These settings are used as the default value unless overloaded. As a supplement to the configuration data, these files can save the data required for the application (or multiple applications).

Whenever the application startup reads configuration information, then this information is buffered. Due to buffering, the application can quickly read them, so there is no need to consider the bottleneck of the application, because it often performs some integer information for a text file. In addition, a change in web.config of an application will cause the application to restart. This ensures that modifications to the configuration file information are immediately reflected in the application.

Database connection information, default image path, and XML data file paths are typically saved in a web.config file. The syntax saves the data in the web.config file is as follows, in the ideal case you might want to use the integrated SQL identity verification:

- Application Special Settings -> To access values ​​in the ASP.NET page, you can use the ConfigurationSettings collection, which is in the System.configuration namespace. The following simple example demonstrates how to extract the previous connection string into a local variable:

Using system.configuration; ooostring strconnstring = configurationSettings.appsettings ["connectionstring"];

Add a reference to System.Configuration namespace to reduce the number of codes that reference these values. Because modifications to Web.config or Machine.config will cause the application to reboot immediately, these values ​​are only manually modified by the server system administrator. So you can think that these files are a good location that saves read-only data instead of modified data in the application.

in conclusion

Effective status management means that the identified user experience, data error and fast pages or transaction processing are huge differences. Although state management is not applicable in ASP 3.0, ASP.NET brings it to the control of the status object discussed herein. Carefully use them will show you the best web experience.

转载请注明原文地址:https://www.9cbs.com/read-101729.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.044, SQL: 9