通过csdn中sp1234的帖子进行整理
ViewstateMethod.cs
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Threading;
/// <summary>
///ViewstateMethod 的摘要说明
/// </summary>
namespace Lear
{
public class ViewstateMethod : System.Web.UI.Page
{
#region 解决ViewState过于庞大的问题
protected override object LoadPageStateFromPersistenceMedium()
{
string viewStateID = (string)((Pair)base.LoadPageStateFromPersistenceMedium()).Second;
string stateObject = (string)Cache[viewStateID];
if (stateObject != null)
{
Cache.Remove(viewStateID);
return stateObject;
}
string fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
string stateStr = File.ReadAllText(fn);
return new ObjectStateFormatter().Deserialize(stateStr);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
string viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码
Cache.Insert(viewStateID, state);
//ThreadPool.QueueUserWorkItem(obj =>
//{
string value = new ObjectStateFormatter().Serialize(state);
string fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
File.WriteAllText(fn, value);
//});
base.SavePageStateToPersistenceMedium(viewStateID);
}
#endregion
}
}
定时删除Viewstate文件方法,在Page_Load中调用,时间自行调整,建议放在root.master.cs文件中(最外层的模版)
View Code
#region 删除ViewState中过时的信息
private void DelViewstateForApplication()
{
if (Application["delDatetime"] != null)
{
DateTime thisNow = System.DateTime.Now;
DateTime lastNow = thisNow;
DateTime delDatetime = Convert.ToDateTime(Application["delDatetime"]);
if ((thisNow - delDatetime).Minutes > 1)//时间自行调整
{
lock (Application)
{
if (delDatetime == Convert.ToDateTime(Application["delDatetime"]))
{
lastNow = Convert.ToDateTime(Application["delDatetime"]);
Application["delDatetime"] = System.DateTime.Now;
}
}
}
if (thisNow != lastNow)
DelViewStateData();
}
else
{
bool first = false;
lock (Application)
{
if (Application["delDatetime"] == null)
{
Application["delDatetime"] = System.DateTime.Now;
first = true;
}
}
if (first)
DelViewStateData();
}
}
private void DelViewStateData()
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(this.Server.MapPath("~/App_Data/ViewState/"));
if (!dir.Exists)
dir.Create();
else
{
DateTime nt = DateTime.Now.AddMinutes(-1);//时间自行调整
foreach (System.IO.FileInfo f in dir.GetFiles())
{
if (f.CreationTime < nt)
f.Delete();
}
}
}
#endregion
最终aspx页面使用方法:如default.aspx.cs文件中的类需要继承自Lear.ViewstateMethod,而不是System.Web.UI.Page
没有交互提交的页面,可在头部Page中加入EnableViewState="false"以减小数据大小,直接继承System.Web.UI.Page,而不继承自Lear.ViewstateMethod生成多余的Viewstate文件。
正常的页面可以关掉EnableViewState="false" EnableViewStateMac="false" EnableEventValidation="false"
注:本方法只是个人总结,请慎重使用。