让ViewState 保存于服务器端文件 (asp.net C#)

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

创建一个基类:


public class
 BasePage : System.Web.UI.Page
{

 protected override object
 LoadPageStateFromPersistenceMedium()
 {
     var viewStateID = (string)((Pair)base.LoadPageStateFromPersistenceMedium()).Second;
     var stateStr = (string)Cache[viewStateID];
     if (stateStr == null)
     {
         var 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)
 {
     var value = new ObjectStateFormatter().Serialize(state);
     var viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码

     var fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
     ThreadPool.QueueUserWorkItem(obj => File.WriteAllText(fn, value));
     Cache.Insert(viewStateID, value);
     base.SavePageStateToPersistenceMedium(viewStateID);
 }
      

    }
}

Global.asax,以下代码也可以不用:


protected void
 Application_Start(object sender, EventArgs e)
{
        DirectoryInfo dir = new DirectoryInfo(this.Server.MapPath("~/App_Data/ViewState/"));
        if (!dir.Exists)
            dir.Create();
        else
        {
            DateTime nt = DateTime.Now.AddHours(-0.3); //删除15分钟以前的缓存文件

            FileInfo[] fiArr = dir.GetFiles();
            foreach (FileInfo f in fiArr)
            {

                if (f.CreationTime < nt)
                {
                    f.Delete();
                }
            }
        }
    }

使用方法:
其它页面继承自BascPage即可

你可能感兴趣的:(object,String,服务器,C#,asp.net,磁盘)