把viewstate保存在服务器上
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.IO;
/// <summary>
///ViewStateToDisk 的摘要说明
/// </summary>
public class ViewStateToDisk : System.Web.UI.Page//继承Page类
{
protected override object LoadPageStateFromPersistenceMedium()
{
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);
}
return new ObjectStateFormatter().Deserialize(stateStr);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
string value = new ObjectStateFormatter().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中加如下代码:
void Application_Start(object sender, EventArgs e)
{
//在应用程序启动时运行的代码
System.IO.DirectoryInfo dir = new System.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的页面继承我们上面改写的类了。