您的位置:首页 > 其它

ViewState 剖析

2006-01-19 11:41 507 查看
(以前我在 csdn 写的翻译文章,现在转到这里来。)

ViewState 剖析


原文链接:ViewState: All You Wanted to Know
作者:Paul Wilson翻译:木野狐


ViewState 不是什么?


1. ViewState 不是用来恢复回发的控件的值。
这个是通过匹配 form 中该控件的变量名而自动完成的。这个只对 Load 事件加载之前创建的控件有效。
2. ViewState 不会自动重新创建任何通过代码动态创建的控件。
3. 不是用来保存用户信息的。仅仅保存本页的控件状态,而不能在页面之间传递。

ViewState 是什么?

ViewState 用来跟踪和保存控件的状态信息。否则这些信息可能会丢失,原因可能是这些值不随着 form 回发,或者根本就不在 page 的 html 中。
ViewState 中保存着代码中改变的控件属性,通过代码绑定到控件的任何数据,以及由用户操作触发,回发的任何更改。
ViewState 还提供了一个状态包(StateBag), 这是一个特殊的集合或字典(collection or dictionary), 可以用来保存,通过一个 key 来恢复任意的对象或者值。

ViewState 的格式

保存在表单中的 __VIEWSTATE 隐藏字段。是 Base64 编码过的,而不是加密!
但要加密也是可以的(设置 enableViewStateMac 来使用 machine key 进行 hash)
加密:设置 machineKey 验证, 但这必须在机器级别设置,需要更多的资源,所以不推荐。

Listing 1: ViewState Machine Hash Disabled
machine.config or web.config: <pages enableViewStateMac='false' />
page level directive:         <%@Page enableViewStateMac='false' %>
page level script code:       Page.EnableViewStateMac = false;


Listing 2: ViewState Encryption is Enabled
machine.config: <machineKey validation='3DES' validationKey='*' />
where the validationKey must be the same across a web-farm setup
also requires the enableViewStateMac property setting to be true

在 rendering 之前,ViewState 在 Page.SavePageStateToPersistenceMedium 方法中被保存,
回发时,在 Page.LoadPageStateFromPersistanceMedium 方法中被恢复。
这两个方法都可以轻易的被重写,从而实现保存 ViewState 到 Session 中。这适合于带宽小的场合,
如移动设备默认是采用 Session.代码如下:

Listing 3: ViewState Saved in Session State
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["ViewState"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["ViewState"] = viewState;
// Bug requires Hidden Form Field __VIEWSTATE
RegisterHiddenField("__VIEWSTATE", "");
}
如果要把 ViewState 通过数据库或其他持久化设备来维持,则需要采用特定的 LosFormatter 类来序列化,反序列化。(serialize, deserialize)


Listing 4: ViewState Saved in Custom Store
protected override object LoadPageStateFromPersistenceMedium()
{
LosFormatter format = new LosFormatter();
return format.Deserialize(YourDataStore["ViewState"]);
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
LosFormatter format = new LosFormatter();
StringWriter writer = new StringWriter();
format.Serialize(writer, viewState);
YourDataStore["ViewState"] = writer.ToString();
}

最后,我们来看一下 ViewState 的内部格式到底是什么。
每个控件的 ViewState 保存在一个三元组中(Triplet, System.Web.UI.Triplet).
其 First 对象是:
一个 Pair(System.Web.UI.Pair)
或
Array or Pairs, of ArrayLists of related name-values.
Second 对象:
该控件在控件树中的索引的 ArrayList
Third 对象:
子控件的类似的三元组的 ArrayList


Listing 5: ViewState Decode/Parse Example
编码后的 ViewState:
dDwxMjM0NTY3ODkwO3Q8cDxsPHBycEE7cHJwQjtwcnBDOz47bDx2YWxBO3ZhbEI7dmFsQzs+PjtsPGk8
MD47aTwyPjtpPDM+O2k8NT47PjtsPHQ8cDxsPHBycEE7cHJwQjs+O2w8dmFsQTt2YWxCOz4+Ozs+O3Q8
cDxsPHBycEE7cHJwQjs+O2w8dmFsQTt2YWxCOz4+Ozs+O3Q8cDxsPHBycEE7cHJwQjs+O2w8dmFsQTt2
YWxCOz4+Ozs+O3Q8cDxsPHBycEE7cHJwQjs+O2w8dmFsQTt2YWxCOz4+Ozs+Oz4+Oz4=

解码后的 ViewState:
t<1234567890;t<p<l<prpA;prpB;prpC;>;l<valA;valB;valC;>>;
l<i<0>;i<2>;i<3>;i<5>;>;l<
t<p<l<prpA;prpB;>;l<valA;valB;>>;;>;
t<p<l<prpA;prpB;>;l<valA;valB;>>;;>;
t<p<l<prpA;prpB;>;l<valA;valB;>>;;>;
t<p<l<prpA;prpB;>;l<valA;valB;>>;;>;>>;>

解析后的 ViewState:
t<1234567890;             页面级别的三元组是特例
t<p<l<prpA;prpB;prpC;>; Triplet-First:Pair-First:ArrayList
l<valA;valB;valC;>                Pair-Second:ArrayList
>;
l<i<0>;               Triplet-Second:ArrayList:Indices
i<2>;                                        of the
i<3>;                                        Children
i<5>;                                        Controls
>;
l<t<p<l<prpA;prpB;>;  Triplet-Third:ArrayList:Triplets
l<valA;valB;>                           of the
>;                                       Children
;                                          Controls
>;
t<p<l<prpA;prpB;>;  Each Sub-Triplet follows same Pattern
l<valA;valB;>
>;
;                  More Levels Possible if sub-Children
>;
t<p<l<prpA;prpB;>;  Each Sub-Triplet follows same Pattern
l<valA;valB;>
>;
;                  More Levels Possible if sub-Children
>;
t<p<l<prpA;prpB;>;  Each Sub-Triplet follows same Pattern
l<valA;valB;>
>;
;                  More Levels Possible if sub-Children
>;
>
>;                     Closing of Special Page-Level Triplet
>


Listing 6: ViewState Decode/Parse Code
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Web.UI;

namespace MyPlayground
{
public class ShowViewState : Page
{
private void Page_Load(object sender, EventArgs e)
{
//Trace.Warn("分类名称", "^_^,这是警告!自动用红色字显示");
//Trace.Write("这是普通的消息写入!");
}

#region Web 窗体设计器生成的代码

protected override void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}

#endregion

protected override void SavePageStateToPersistenceMedium(object viewState)
{
// 调用基类的方法以便不影响正常的处理
base.SavePageStateToPersistenceMedium(viewState);
// 读取 ViewState 并写到页面
LosFormatter format = new LosFormatter();
StringWriter writer = new StringWriter();
format.Serialize(writer, viewState);
string vsRaw = writer.ToString();
Response.Write("ViewState Raw: " + Server.HtmlEncode(vsRaw) + "<hr>");
// 解码 ViewState 并写到页面
byte[] buffer = Convert.FromBase64String(vsRaw);
string vsText = Encoding.ASCII.GetString(buffer);
Response.Write("ViewState Text: " + Server.HtmlEncode(vsText) + "<hr>");
// 解析 ViewState -- 打开页面跟踪(Tracing)
ParseViewState(viewState, 0);
}

private void ParseViewState(object vs, int level)
{
if (vs == null)
Trace.Warn(level.ToString(), Spaces(level) + "null");
else if (vs.GetType() == typeof (Triplet))
{
Trace.Warn(level.ToString(), Spaces(level) + "Triplet");
ParseViewState((Triplet) vs, level);
}
else if (vs.GetType() == typeof (Pair))
{
Trace.Warn(level.ToString(), Spaces(level) + "Pair");
ParseViewState((Pair) vs, level);
}
else if (vs.GetType() == typeof (ArrayList))
{
Trace.Warn(level.ToString(), Spaces(level) + "ArrayList");
ParseViewState((IEnumerable) vs, level);
}
else if (vs.GetType().IsArray)
{
Trace.Warn(level.ToString(), Spaces(level) + "Array");
ParseViewState((IEnumerable) vs, level);
}
else if (vs.GetType() == typeof (String))
Trace.Warn(level.ToString(), Spaces(level) + "'" + vs.ToString() + "'");
else if (vs.GetType().IsPrimitive)
Trace.Warn(level.ToString(), Spaces(level) + vs.ToString());
else
Trace.Warn(level.ToString(), Spaces(level) + vs.GetType().ToString());
}

private void ParseViewState(Triplet vs, int level)
{
ParseViewState(vs.First, level + 1);
ParseViewState(vs.Second, level + 1);
ParseViewState(vs.Third, level + 1);
}

private void ParseViewState(Pair vs, int level)
{
ParseViewState(vs.First, level + 1);
ParseViewState(vs.Second, level + 1);
}

private void ParseViewState(IEnumerable vs, int level)
{
foreach (object item in vs)
ParseViewState(item, level + 1);
}

// 得到指定数目的空白
private string Spaces(int count)
{
string spaces = "";
for (int index = 0; index < count; index++)
spaces += "   ";
return spaces;
}
}
}

译注:上面代码由本人测试后加上了 VS.NET 自动生成的其他部分代码,为方便大家试验。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: