I,Use hidden Domains
Session, application, and cache are all stored in the server memory. Generally, we do not have the right to access the client machine and store the data directly on the client (cookie is an exception, but the cookie can only store strings of no more than 4 K ). Where can we save data temporarily? That is the page! If we place a label control on the web page and set it to hide. Then we can use this label to save some temporary data for the program on the current page.
In ASP. NET, we can also use hidden domains for similar work. Unlike label, the content entered in the hidden domain is not directly displayed in the IDE design view. Because the data we save does not need to be displayed to users at all, it is more reasonable to use hidden domains.
<Asp: hiddenfield id = "hiddenfield1" runat = "server" value = "happy programming"/>
In the code, you can directly access the Value Attribute of the hidden domain to obtain its value.
Response. Write (hiddenfield1.value );
However, there are still a few unreasonable points.
· Data is directly exposed to users.
· Only string data can be stored.
II,Use
Viewstate
ASP. NET introduces the viewstate concept. We can probably see from this name that viewstate is mainly used to store some view-related states. For example, when a user registers, the user fills in a lot of data. After the user submits the page, the system returns an error message indicating "Duplicate User names, at this time, all the registration materials you entered on the previous page are missing. What do users feel like? I think most users will be annoyed. ASP. NET automatically saves the control status through viewstate. You may also find that the data in the text box still exists after the page is submitted.
At the same time, we can also use viewstate to save the data required by some programs. The data in viewstate is base64 encoded by default. Therefore, you cannot directly view the data in viewstate. We can add a viewstate item in the Code as follows:
Viewstate ["test"] = "happy programming ";
Open the page and observe the source code. viewstate is here:
<Input type = "hidden" name = "_ viewstate" id = "_ viewstate" value = "XT + q3ccgrb + qjuknb1n7x
Cmugamjbpmawtmtwpe + b5ii8urfao42agkyr + u9t0be "/>
Since viewstate exists on a page, viewstate cannot be used across pages, and the viewstate accessed by each user is independent. In addition, viewstate does not have the concept of declaring a period. The page is in viewstate, and the page is closed when viewstate is disabled.
Looking at the viewstate above, can't you find the shadow of the word "happy programming? Add a button on the page. The button's Click Event processing method is as follows:
Response. Write (system. Text. encoding. utf8.getstring (convert. frombase64string (
Request ["_ viewstate"]);
5-1. After you click the button, the page is displayed as follows.
Figure 5-1 perform base64 decoding on viewstate data
After base64 Decoding of viewstate data, we can see the words "happy programming. However, the string is still messy. In fact, ASP. NET first serializes viewstate data, and then uses base64 encoding to store the data in the hidden domain of the page. Base64 is not an encryption algorithm, but an encoding algorithm. Anyone can perform anti-encoding on base64.
III,
ViewstateSecurity and Performance
If we need to save relatively confidential data in viewstate (of course, we do not recommend that you store very confidential data in viewstate), how can we ensure the security of viewstate? Generally, you can start from two aspects.
1. Make sure that the viewstate submitted by the client is not modified. We need to be aware of the fact that everything on the client is untrustworthy as we do web applications. You may think that users can modify the settings only when we provide controls such as textbox. In fact, this is wrong. Although the content in the dropdownlist can only be selected and cannot be modified, it can completely forge a page for submission. The same applies to viewstate. For further security, we need to verify that the viewstate sent back by the client has been modified.
2. Make sure that you cannot directly view the data in viewstate. To put it bluntly, the viewstate is encrypted.
In ASP. NET 2.0, you only need to perform simple configuration to verify and encrypt viewstate. In the header of the page, add the enableviewstatemac (verification) and viewstateencryptionmode (encryption) attributes:
<% @ Page Language = "C #"... Enableviewstatemac = "true" viewstateencryptionmode = "always" %>
Of course, if you want to apply verification and encryption to viewstate on all pages, you can add:
<Pages enableviewstatemac = "true" viewstateencryptionmode = "always"> </pages>
Since the data in viewstate is added after serialization, we can store some complex types in viewstate. When we introduced the session, we once created a myuser custom class and stored its instances in the session. Later, in order to make the StateServer and sqlserver mode sessions Save the myuser type, we also marked [serializable] For myuser. To save the custom type in viewstate, you also need to mark [serializable] As the type. Here we use viewstate to save the code of the myuser instance and use session.
Myuser user = new myuser ();
User. susername = "Xiao Zhu ";
User. iaage = 24;
Viewstate ["customclass"] = user;
Read code:
Myuser user = viewstate ["customclass"] As myuser;
Response. Write (user. tostring ());
How much data can be stored in viewstate? For the moment, there is an upper limit on the size of form post data. viewstate is serialized and encoded and stored on the page. If we store a dataset with 100 records in viewstate, it is difficult to open the page. Believe it or not, you can perform a test on your own.
Dataset DS = new dataset ();
Using (sqlconnection conn = new sqlconnection (@ "Server = (local)" sqlexpress; database =
Forum; trusted_connection = true "))
{
Sqldataadapter da = new sqldataadapter ("select Top 100 * From cachetest", Conn );
Da. Fill (DS );
}
Viewstate ["data"] = Ds;
There are only 100 records, as shown in viewstate, 5-2.
Figure 5-2 Results of viewstate misuse
In addition, the data must be used between the browser and the server, and the network traffic occupied is objective. Therefore, we recommend that you save as little data as possible in viewstate. If you need to place a large amount of data in viewstatge, we recommend that you use maxpagestate-fieldlength to enable multipart transmission for viewstate.
<% @ Page Language = "C #"... Maxpagestatefieldlength = "100" %>
As shown in Figure 5-3, a single viewstate is set. The viewstate consists of up to 100 bytes.
Figure 5-3 Use maxpagestatefieldlength to control a viewstate of no more than 100 bytes
We know that viewstate is not just in use, Asp. net stores some data related to the control interaction in viewstate, but for some controls that do not implement any interaction (such as the gridview that displays 10 records ), you can set the enableviewstate attribute of the control to false so that the control does not use viewstate, thus reducing the page size.
IV,
ControlStateOverview
Finally, we will briefly mention that ASP. NET 2.0 provides controlState. It is used to save key information of (custom) controls. Even if the viewstate of a page or control is disabled, the viewstate can also be disabled. However, using controlState is a little complicated. We need to serialize complex objects for storage. The following code demonstrates how to save and read simple strings in controlState:
Pagestatepersister. controlState = "happy programming ";
Response. Write (pagestatepersister. controlState. tostring ());
V,Summary
In fact, the principle of hidden domain, viewstate, and controlState is similar. Let's summarize it.
· Physical storage location. Form hidden fields.
· Storage type restrictions. Serializable type (you must serialize the content stored directly in the hidden domain ).
· Range of status usage. The current page (current control), independent of the user.
· Storage size limit. If too much data is stored, the page cannot be opened and cannot be submitted.
· Lifecycle. The page is there, and the page is no longer there. The three are always attached to the hidden domain of the page.
· Security and performance. It is stored on the client and has low security. However, viewstate provides authentication and encryption.
· Advantages and disadvantages and precautions. It is very convenient and simple to store a small amount of data. However, be sure not to store sensitive data or large data. They are different from Cookie, session, and application. Although the cookie is also stored on the client, each commit is appended to the HTTP header for submission, but its data size is not large after all, it plays a role in marking. Both session and application are stored on the server side and will not participate in the page round-trip process. Hidden fields, viewstate, and controlState are always involved in the round-trip, and serialization and deserialization consume certain resources. Therefore, storing too much data will lead to slow webpage loading and waste server bandwidth.