asp.net select session state or ViewState?
In some cases, saving a state value in ViewState is not the best choice, and the most common alternative is session state, which is generally more applicable to:
A lot of data. Because ViewState increases the size of the page that is sent to the browser (the HTML payload) and also increases the size of the returned form, it is not appropriate to store large amounts of data.
Security data that is not displayed in the UI. Although ViewState data has been encoded and can optionally be encrypted, it is safest to never send data to the client. Therefore, a session is a more secure choice. (Because the database requires additional credentials to authenticate, it is more secure to store the data in the database.) You can add SSL to get a more secure link. However, if the private data is already displayed in the UI, you should have confirmed the security of the link. In this case, putting the same value into the ViewState does not degrade security.
An object, such as a DataSet, that has not been serialized into ViewState. The ViewState serializer optimizes only a small number of commonly used object types, as shown below. Other serializable types may be retained in the ViewState, but the speed will be slow and a very large ViewState will be generated.
Session State ViewState
Do you use server resources? Whether
Do you have a timeout? Yes, 20 minutes later (default) No
Do you store all. NET types? Whether, support only: String, Integer, Boolean, Array, ArrayList, Hashtable, and custom TypeConverter
Do you want to increase the HTML payload? No is
Use ViewState for optimal performance
When using ViewState, each object must be serialized into the ViewState and then deserialized by a postback, so the use of ViewState is not without cost. However, if you follow some simple principles to control the cost of ViewState, you typically do not have a significant performance impact.
Disable ViewState when it is not needed. This issue is described in more detail in the "Reducing Use of ViewState" section below.
Use an optimized ViewState serializer. The types listed above have specialized serializers that run quickly and are optimized to produce small ViewState. If you want to serialize a type that is not listed above, you can create a custom typeconverter to significantly improve its performance.
Minimize the use of objects and, if possible, minimize the number of objects placed in ViewState. For example, instead of using a two-dimensional string array (name/value with the same number of objects as the length of an array), use a two string array (only two objects). However, before you store two known types in ViewState, there is no performance improvement between the two, because doing so is actually equivalent to the cost of two conversions.
Reduce the use of ViewState
ViewState is enabled by default and is determined by each control, not the page developer, to determine what is stored in the ViewState. Sometimes, this information is of little use to the application. While it's harmless, it can significantly increase the size of the pages sent to the browser. So if you don't need to use ViewState, it's best to turn it off, especially when the ViewState is big.
You can turn off ViewState on a per-control, per-page, or per-application basis. ViewState will no longer be required in the following situations:
Page control
The page is not passed back to itself.
The event that is not handled by the control.
Controls do not have dynamic or data-bound property values (or are set in code for each request).
The DataGrid control is a heavyweight user of ViewState. By default, all the data displayed in the grid is stored in ViewState, which is useful when a complex operation (such as a complex search) is needed to get the data. However, this behavior of the DataGrid sometimes makes ViewState a liability.
For example, here's a simple page that falls into this scenario. Because the page is not passed back to itself, it does not need ViewState.
Figure 3: A simple page with DataGrid1 lessviewstate.aspx
Private Sub Page_Load (sender as Object, E as EventArgs)
Dim DS as New DataSet ()
Ds. READXML (Server.MapPath ("Testdata.xml"))
DataGrid1.DataSource = ds
Datagrid1.databind ()
End Sub
</script>
When ViewState is enabled, this small grid adds more than 3,000 bytes of HTML payload to the page! You can see this clearly by using ASP.net tracing (English) or by viewing the source code of the page sent to the browser, as shown in the following code.
Disable ViewState
In the example above, I disabled ViewState by setting the grid's EnableViewState property to False. You can disable ViewState for a single control, an entire page, or an entire application, as follows:
Each control (on the tag) <asp:datagrid enableviewstate= "false"?/>
Each page (in the Directive) <%@ page enableviewstate= "False"?%>
Each application (in Web.config) <pages enableviewstate= "false"?/>
Make ViewState more secure
Since ViewState is not formatted as clear text, some people sometimes think it is encrypted, but not. Instead, ViewState only Base64 encoding to ensure that the value does not change during the round trip, regardless of the response/request encoding used by the application.
You can add two kinds of ViewState security levels to your application:
Tamper Resistant
Encryption
It should be noted that ViewState security has a direct impact on the time it takes to process and render asp.net pages. Simply put, the higher the security, the slower the speed. Therefore, do not add security for ViewState if you do not need it.
Tamper Resistant
Although the hash code does not guarantee the security of the actual data in the ViewState field, it can significantly reduce the likelihood that someone has cheated an application through ViewState, that is, preventing the return application from generally prohibiting the user from entering a value.
You can instruct ASP.net to append a hash code to the ViewState field by setting the enableViewStateMac property:
<% @Page enableviewstatemac=true%>
You can set enableViewStateMac at the page level or at the application level. At the time of return, ASP.net will generate a hash code for the ViewState data and compare it to the hash code stored in the postback value. If two hash codes do not match, the ViewState data is discarded and the control reverts to its original setting.
By default, ASP.net uses the SHA1 algorithm to generate the ViewState hash code. Alternatively, you can select the MD5 algorithm by setting <machineKey> in the Machine.config file, as follows:
<machinekey validation= "MD5"/>
Encryption
You can use encryption to protect the actual data values in the ViewState field. First, you must set enableviewstatmac= "true" as described above. Then, set the MachineKey validation type to 3DES. This instructs ASP.net to use the Triple DES symmetric encryption algorithm to encrypt the ViewState value.
<machinekey validation= "3DES"/>
ViewState security in the WEB domain
By default, ASP.net creates a random authentication key and is stored in the Local Security Authority (LSA) for each server. To verify the ViewState field created on another server, the validationkey of the two servers must be set to the same value. If you want to ViewState security settings for applications running in the WEB domain configuration in one of these ways, you need to provide a unique, shared authentication key for all servers.
The validation key is a random string of 20 to 64-bit password-enhanced bytes, expressed in 40 to 128 hexadecimal characters. The longer the key is secure, the 128-character key is recommended (if supported by the computer). For example:
The System.Security.Cryptography namespace includes the RNGCryptoServiceProvider class, which can be used to generate this string, as shown in the following generatecryptokey.aspx example:
Place the user code to initialize the page here
byte[] buff = new BYTE[KEYLENGTH/2];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();
The array is populated with password-enhanced random bytes
Rng. GetBytes (Buff);
StringBuilder sb = new StringBuilder (keylength);
int i;
for (i = 0; i < buff. Length; i++) {
Sb. Append (String.Format ("{0:x2}", Buff[i));
}
Paste into a text box where users can copy
TextBox1.Text = sb. ToString ();
}
</script>
Summarize
ASP.net ViewState is a new state service that allows developers to track UI state based on each user. ViewState is no mystery, it just uses an old Web programming trick: To pass the state back and forth in a hidden form field and apply it directly to the page-handling frame. But the effect is very good-just write and maintain very little code in a web-based form.
The user may not always need it, but I think you'll find that when you need it, ViewState is a very satisfying feature of the many ASP.net new features available to page developers.
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.