把viewstate保存在服务器上

将ViewState持久化保持在服务器端的代码,这样ViewState不占用网络带宽,因此其存取只是服务器的磁盘读取时间。并且它很小,可以说是磁盘随便转一圈就能同时读取好多ViewState,因此可以说“不占时间”。为了“不占磁盘时间”,还可以使用了缓存。

 
新建一个类,命名为ViewStateToDisk,继承Page类,代码如下:

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);
}

}

然后在Global.asax中加如下代码:

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();
}
}
}

上述步骤做好后,就可以在你需要处理viewstate的页面继承我们上面改写的类了。
如:
index.aspx.cd中
public partial class index : System.Web.UI.Page
{
页面是继承System.Web.UI.Page的,只需要把它改成
public partial class index :ViewStateToDisk
{
}
就可以了,这时运行你的网站,你会发现viewstate已经存在你的目录中去了,并且页面中viewstate再也不会一大堆了,如下图:
 
viewstate未保存在服务器磁盘的截图
viewstate保存在磁盘的截图
posted @ 2012-11-10 11:02  Devin0613  阅读(162)  评论(0编辑  收藏  举报