Preliminary study on ASP.net ViewState (3) from MSDN

Source: Internet
Author: User
Tags config hash md5 new features sha1
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

<%@ Import namespace= "System.Data"%>
<body>
<form runat= "Server" >
<asp:datagrid runat= "Server"/>
</form>
</body>
<script runat= "Server" >

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.

<HTML>
<HEAD>
<title> reduce page "HTML payload" </title>
</HEAD>
<body>
<form name= "_ctl0" method= "post" action= "lessviewstate.aspx" id= "_ctl0" >
<input type= "hidden" name= "__viewstate"
Value= "Ddwxntgzotu2oda7ddw7bdxppde+oz47bdx0pdtspgk8mt47pjtsphq8qda8cdxw
pgw8ugfnzunvdw50o18hsxrlbunvdw50o18hrgf0yvnvdxjjzul0zw1db3vuddteyxrhs2v
5czs+o2w8atwxpjtppdg+o2k8od47bdw+oz4+oz47ozs7ozs7oztamdxamdxwpgw8sgvhzg
Vyvgv4ddteyxrhrmllbgq7u29ydev4chjlc3npb247umvhze9ubhk7pjtsphb1yl9pzdtwd
Wjfawq7chvix2lko288zj47pj47ozs7pjtamdxwpgw8sgvhzgvyvgv4ddteyxrhrmllbgq7
U29ydev4chjlc3npb247umvhze9ubhk7pjtsphb1yl9uyw1lo3b1yl9uyw1lo3b1yl9uyw1
Lo288zj47pj47ozs7pjtamdxwpgw8sgvhzgvyvgv4ddteyxrhrmllbgq7u29ydev4chjlc3
Npb247umvhze9ubhk7pjtspgnpdhk7y2l0ettjaxr5o288zj47pj47ozs7pjtamdxwpgw8s
Gvhzgvyvgv4ddteyxrhrmllbgq7u29ydev4chjlc3npb247umvhze9ubhk7pjtsphn0yxrl
O3n0yxrlo3n0yxrlo288zj47pj47ozs7pjtamdxwpgw8sgvhzgvyvgv4ddteyxrhrmllbgq
7u29ydev4chjlc3npb247umvhze9ubhk7pjtspgnvdw50cnk7y291bnryettjb3vudhj5o2
88zj47pj47ozs7pjs+oz47bdxppda+oz47bdx0pdtspgk8mt47atwypjtppdm+o2k8nd47a
Tw1pjtppdy+o2k8nz47atw4pjs+o2w8ddw7bdxppda+o2k8mt47atwypjtppdm+o2k8nd47
Pjtsphq8cdxwpgw8vgv4dds+o2w8mdcznjs+pjs+ozs+o3q8cdxwpgw8vgv4dds+o2w8tmv
3ie1vb24gqm9va3m7pj47pjs7pjt0pha8cdxspfrlehq7pjtspejvc3rvbjs+pjs+ozs+o3
Q8cdxwpgw8vgv4dds+o2w8tue7pj47pjs7pjt0pha8cdxspfrlehq7pjtspfvtqts+pjs+o
Zs+oz4+o3q8o2w8atwwpjtppde+o2k8mj47atwzpjtppdq+oz47bdx0pha8cdxspfrlehq7
Pjtspda4nzc7pj47pjs7pjt0pha8cdxspfrlehq7pjtspejpbm5ldcamiehhcmrszxk7pj4
7pjs7pjt0ph_u56? Cdxspfrlehq7pjtspfdhc2hpbmd0b247pj47pjs7pjt0pha8cdxspfrlehq7pjtsperdoz
4+oz47oz47ddxwpha8bdxuzxh0oz47bdxvu0e7pj47pjs7pjs+pjt0pdtspgk8md47atwxp
Jtppdi+o2k8mz47atw0pjs+o2w8ddxwpha8bdxuzxh0oz47bdwxmzg5oz4+oz47oz47ddxw
Pha8bdxuzxh0oz47bdxbbgdvzgf0ysbjbmzvc3lzdgvtczs+pjs+ozs+o3q8cdxwpgw8vgv
4dds+o2w8qmvya2vszxk7pj47pjs7pjt0pha8cdxspfrlehq7pjtspenboz4+oz47oz47dd
Xwpha8bdxuzxh0oz47bdxvu0e7pj47pjs7pjs+pjt0pdtspgk8md47atwxpjtppdi+o2k8m
Z47atw0pjs+o2w8ddxwpha8bdxuzxh0oz47bdwxnjiyoz4+oz47oz47ddxwpha8bdxuzxh0
Oz47bdxgaxzliexha2vzifb1ymxpc2hpbmc7pj47pjs7pjt0pha8cdxspfrlehq7pjtspen
Oawnhz287pj47pjs7pjt0pha8cdxspfrlehq7pjtspelmoz4+oz47oz47ddxwpha8bdxuzx
H0oz47bdxvu0e7pj47pjs7pjs+pjt0pdtspgk8md47atwxpjtppdi+o2k8mz47atw0pjs+o
2w8ddxwpha8bdxuzxh0oz47bdwxnzu2oz4+oz47oz47ddxwpha8bdxuzxh0oz47bdxsyw1v
Bmeguhvibglzagvyczs+pjs+ozs+o3q8cdxwpgw8vgv4dds+o2w8rgfsbgfzoz4+oz47oz4
7ddxwpha8bdxuzxh0oz47bdxuwds+pjs+ozs+o3q8cdxwpgw8vgv4dds+o2w8vvnboz4+oz
47oz47pj47ddw7bdxppda+o2k8mt47atwypjtppdm+o2k8nd47pjtsphq8cdxwpgw8vgv4d
Ds+o2w8otkwmts+pjs+ozs+o3q8cdxwpgw8vgv4dds+o2w8r0dhjkc7pj47pjs7pjt0pha8
Cdxspfrlehq7pjtspe3dvg5jagvuoz4+oz47oz47ddxwpha8bdxuzxh0oz47bdwmbmjzcfw
7oz4+oz47oz47ddxwpha8bdxuzxh0oz47bdxhzxjtyw55oz4+oz47oz47pj47ddw7bdxppd
A+o2k8mt47atwypjtppdm+o2k8nd47pjtsphq8cdxwpgw8vgv4dds+o2w8otk1mjs+pjs+o
Zs+o3q8cdxwpgw8vgv4dds+o2w8u2nvb3ruzxkgqm9va3m7pj47pjs7pjt0pha8cdxspfrl
ehq7pjtspe5ldybzb3jroz4+oz47oz47ddxwpha8bdxuzxh0oz47bdxowts+pjs+ozs+o3q
8cdxwpgw8vgv4dds+o2w8vvnboz4+oz47oz47pj47ddw7bdxppda+o2k8mt47atwypjtppd
M+o2k8nd47pjtsphq8cdxwpgw8vgv4dds+o2w8otk5ots+pjs+ozs+o3q8cdxwpgw8vgv4d
Ds+o2w8thvjzxjuzsbqdwjsaxnoaw5noz4+oz47oz47ddxwpha8bdxuzxh0oz47bdxqyxjp
Czs+pjs+ozs+o3q8cdxwpgw8vgv4dds+o2w8jm5ic3bcozs+pjs+ozs+o3q8cdxwpgw8vgv
4dds+o2w8rnjhbmnloz4+oz47oz47pj47pj47pj47pj47pj47pg== "/>

See! The ViewState of the grid is disabled, and the payload of the same page is greatly reduced:

<HTML>
<HEAD>
<title> reduce page "HTML payload" </title>
</HEAD>
<body>
<form name= "_ctl0" method= "post" action= "lessviewstate.aspx" id= "_ctl0" >
<input type= "hidden" name= "__viewstate" value= "ddwxntgzotu2oda7oz4="/>

Here is the complete lessviewstate code for Visual Basic and C #:

[Visual Basic]
<%@ Import namespace= "System.Data"%>
<HEAD>
<title> reduce page "HTML payload" </title>
</HEAD>
<body>
<form runat= "Server" >
<H3>
Reduce page "HTML payload" by disabling ViewState
</H3>
<P>
<asp:datagrid id= "DATAGRID1" runat= "Server" enableviewstate= "false"
Borderstyle= "None" borderwidth= "1px" bordercolor= "#CCCCCC"
Backcolor= "White" cellpadding= "5" >
</HeaderStyle>
</asp:datagrid>
</P>
</form>
</body>

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>

[C #]
<%@ Page language= "C #"%>
<%@ Import namespace= "System.Data"%>
<HEAD>
<title> reduce page "HTML payload" </title>
</HEAD>
<body>
<form runat= "Server" >
<H3>
Reduce page "HTML payload" by disabling ViewState
</H3>
<P>
<asp:datagrid id= "DATAGRID1" runat= "Server" enableviewstate= "false"
Borderstyle= "None" borderwidth= "1px" bordercolor= "#CCCCCC"
Backcolor= "White" cellpadding= "5" >
</HeaderStyle>
</asp:datagrid>
</P>
</form>
</body>
<script runat= "Server" >

void Page_Load (object sender, EventArgs e) {

DataSet ds = new DataSet ();
Ds. READXML (Server.MapPath ("Testdata.xml"));

DataGrid1.DataSource = ds;
Datagrid1.databind ();
}

</script>

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:

<machinekey validation= "SHA1" validationkey= "
f3690e7a3143c185ab1089616a8b4d81fd55dd7a69eeaa3b32a6ae813eceecd28dea66a
23bee42193729bd48595ebafe2c2e765be77e006330bc3b1392d7c73f "/>

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:

<%@ Page language= "C #"%>
<%@ Import namespace= "System.Security.Cryptography"%>
<HTML>
<body>
<form runat= "Server" >
<H3> generate random encryption key </H3>
<P>
<asp:radiobuttonlist id= "RadioButtonList1"
runat= "Server" repeatdirection= "Horizontal" >
<asp:listitem value= ">40-byte</asp:ListItem>"
<asp:listitem value= "128" selected= "True" >128-byte</asp:ListItem>
</asp:RadioButtonList>
<asp:button id= "Button1" runat= "Server" onclick= "GenerateKey"
text= "Generate Key" >
</asp:Button></P>
<P>
<asp:textbox id= "TextBox1" runat= "Server" textmode= "MultiLine"
Rows= "columns=" backcolor= "#EEEEEE" enableviewstate= "False" >
Copy and paste the results of the build </asp:TextBox></P>
</form>
</body>
</HTML>


<script runat=server>

void GenerateKey (object sender, System.EventArgs e)
{
int keylength = Int32.Parse (RadioButtonList1.SelectedItem.Value);

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.



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.