ASP.NET里不可避免的要用上viewstate,怎么用它估计大家都用得烂熟了,它的优点缺点用过的人也能说出个大概.其中被说得最多的还是它的缺点,viewstate的使用使得页面大小长胖了好几KB,甚至上M,最直接的效应就是使得页面的加载异常的缓慢.因此对于viewstate的使用及优化是那些ASPDotNet优化教程里谈论得较多的,至于那些怎么禁用viewstate,缓存策略等也就不详细讨论了.
如果不嫌IO操作慢,并且服务器也够地方放,何不把viewstate的内容保存在服务器上,这样可以实现客户端页面的viewstate大小为0,实现起来也很简单,只不过是重写了Page类的两个虚方法SavePageStateToPersistenceMedium和LoadPageStateFromPersistenceMedium,以下是简单的实现方法.
![](/Images/OutliningIndicators/ContractedBlock.gif)
保存viewstate
1
// 对于DotNet 1.1 可采用 LosFormatter
2
ObjectStateFormatter m_stateFormatter;
3
private ObjectStateFormatter StateFormatter
4![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
5
get
6![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
7
if (m_stateFormatter == null)
8![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
9
m_stateFormatter = new ObjectStateFormatter();
10
}
11
return m_stateFormatter;
12
}
13
}
14![](/Images/OutliningIndicators/None.gif)
15![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
16
/// 重写SavePageStateToPersistenceMedium
17
/// 保存viewstate内容到文本中
18
/// </summary>
19
/// <param name="state"></param>
20
protected override void SavePageStateToPersistenceMedium(object state)
21![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
22
FileStream fs = new FileStream(GetFileName(), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
23
StateFormatter.Serialize(fs, state);
24
fs.Close();
25
}
26![](/Images/OutliningIndicators/None.gif)
27![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
28
/// 重写LoadPageStateFromPersistenceMedium
29
/// 从文本中读取viewstate内容
30
/// </summary>
31
/// <returns></returns>
32
protected override object LoadPageStateFromPersistenceMedium()
33![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
34
FileStream fs = new FileStream(GetFileName(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
35
object viewStatObject = StateFormatter.Deserialize(fs);
36
fs.Close();
37
return viewStatObject;
38
}
39![](/Images/OutliningIndicators/None.gif)
40
protected override void OnInit(EventArgs e)
41![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
42
// 给session赋值,以保证每次请求的不创建新的session
43
Session["a"] = "temp";
44
base.OnInit(e);
45
}
46![](/Images/OutliningIndicators/None.gif)
47![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
48
/// 生成并获取文件路径
49
/// </summary>
50
/// <returns></returns>
51
private string GetFileName()
52![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
53
// 以sessionid 和 请求路径 组成 保存viewstate的文件名
54
string url = Request.RawUrl.Replace("/", "");
55
return "E:\\" + Session.SessionID + "_" + url + "_viewstate.txt";
56
}
最后的效果就是,查看页面的html代码,发现viewstate的value是空的.
1 <input type="hidden" name="__VIEWSTATE" id="
2 __VIEWSTATE" value="" />
另外对于Page类还有很多虚方法,好好应用还是挺有趣的.