ViewState压缩技术

时间:2021-06-01 15:49:44

ViewState 的使用,大家可以说是又爱又恨,它其中一个特性就是保存页面的状态,对于只是展示的页面,我们可以直接在页面文件中使用 EnableViewState="false" 来将其屏蔽,但是很多时候,我们不得不使用它,可是它产生的页面冗长的html代码有让我们很头疼,下面介绍一种ViewState压缩机制。主要是通过重写 PageStatePersister 来实现。

1、开发一个ViewStateFactory,根据不同的配置,修改存储方式。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Caching;
namespace Common
{
public enum ViewstateMode
{
Cache,
Session,
Page,
File,
Database
} public class ViewStateFactory
{
public ViewStateFactory()
{
} public static PageStatePersister CreateViewState(ViewstateMode mode, Page page)
{
switch (mode)
{
case ViewstateMode.Cache:
return new CacheStatePersister(page);
case ViewstateMode.Session:
return new SessionPageStatePersister(page);
case ViewstateMode.Page:
case ViewstateMode.File:
case ViewstateMode.Database:
return new HiddenFieldPageStatePersister(page);
default:
return new HiddenFieldPageStatePersister(page);
}
}
} //实现一个自定义的方式,存储到服务器的Cache里
public class CacheStatePersister : PageStatePersister
{
private Cache mCache = HttpRuntime.Cache;
public CacheStatePersister(Page page) : base(page) { } public override void Load()
{
string _vskey = Page.Request.Form["_VIEWSTATE_KEY"];
if (_vskey == null)
{
base.ViewState = null;
}
else
{
base.ViewState = mCache[_vskey];
}
} public override void Save()
{
string _vskey;
_vskey = "VIEWSTATE_" + HttpContext.Current.Session.SessionID + "_" + Page.Request.RawUrl + "_" + System.DateTime.Now.Ticks.ToString(); mCache.Add(_vskey, base.ViewState, null, System.DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
this.Page.RegisterHiddenField("_VIEWSTATE_KEY", _vskey); } } }
  
2、在Web.config的AppSetting里加上
<add key="ViewStateMode" value="Cache"/>  

3、覆盖页面的PageStatePersister,这里你可以开发一个BasePage,在基类里覆盖,所有的页面集成这个页面

        //重写PageStatePersister,用于压缩ViewState
protected override PageStatePersister PageStatePersister
{
get
{
ViewstateMode viewstateMode = ViewstateMode.Page;
try
{
switch (System.Configuration.ConfigurationManager.AppSettings["ViewStateMode"].ToString().ToLower())
{
case "cache":
viewstateMode = ViewstateMode.Cache;
break;
case "session":
viewstateMode = ViewstateMode.Session;
break;
default:
viewstateMode = ViewstateMode.Page;
break;
}
return ViewStateFactory.CreateViewState(viewstateMode, this.Page);
}
catch (Exception ex)
{
return base.PageStatePersister;
}
}
}