把viewstate保存在服务器上
将ViewState持久化保持在服务器端的代码,这样ViewState不占用网络带宽,因此其存取只是服务器的磁盘读取时间。并且它很小,可以说是磁盘随便转一圈就能同时读取好多ViewState,因此可以说“不占时间”。为了“不占磁盘时间”,还可以使用了缓存。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.IO;
/// <summary>
///ViewStateToDisk 的摘要说明
/// </summary>
publicclassViewStateToDisk:System.Web.UI.Page//继承Page类
{
protectedoverrideobjectLoadPageStateFromPersistenceMedium()
{
string viewStateID =(string)((Pair)base.LoadPageStateFromPersistenceMedium()).Second;
string stateStr =(string)Cache[viewStateID];
if(stateStr ==null)
{
string fn =Path.Combine(this.Request.PhysicalApplicationPath,@"App_Data/ViewState/"+ viewStateID);
stateStr =File.ReadAllText(fn);
}
returnnewObjectStateFormatter().Deserialize(stateStr);
}
protectedoverridevoidSavePageStateToPersistenceMedium(object state)
{
string value =newObjectStateFormatter().Serialize(state);
string viewStateID =(DateTime.Now.Ticks+(long)this.GetHashCode()).ToString();//产生离散的id号码
string fn =Path.Combine(this.Request.PhysicalApplicationPath,@"App_Data/ViewState/"+ viewStateID);
//ThreadPool.QueueUserWorkItem(File.WriteAllText(fn, value));
File.WriteAllText(fn, value);
Cache.Insert(viewStateID, value);
base.SavePageStateToPersistenceMedium(viewStateID);
}
}
voidApplication_Start(object sender,EventArgs e)
{
//在应用程序启动时运行的代码
System.IO.DirectoryInfo dir =newSystem.IO.DirectoryInfo(this.Server.MapPath("~/App_Data/ViewState/"));
if(!dir.Exists)
dir.Create();
else
{
DateTime nt =DateTime.Now.AddHours(-1);
foreach(System.IO.FileInfo f in dir.GetFiles())
{
if(f.CreationTime< nt)
f.Delete();
}
}
}