ViewState实现和优化2--自定义压缩方法采用GZipStream压缩

在序列化对象信息前先压缩数据。其实现机制也是重写基类Page 的PageStatePersister 属性

 

代码
public   class  CompressPageStatePersister : PageStatePersister
{
private   string  PageStateKey  =   " ____VIEWSTATE " ;
public  CompressPageStatePersister(Page page) :  base (page)
{}
public   override   void  Load()
{
string  postbackState  =  Page.Request.Form[PageStateKey];
if  ( ! string .IsNullOrEmpty(postbackState))
{
// 页面状态包括视图状态和控件状态两部分
Pair statePair  =  (Pair)CompressHelp.Decompress(postbackState);
if  ( ! Page.EnableViewState)
{
this .ViewState  =   null ;
}
else
{
this .ViewState  =  statePair.First;
}
this .ControlState  =  statePair.Second;
}
}
public   override   void  Save()
{
if  ( ! Page.EnableViewState)
{
this .ViewState  =   null ;
}i
f (
this .ViewState  !=   null   ||   this .ControlState  !=   null )
{
string  stateString;
Pair statePair 
=   new  Pair(ViewState, ControlState);
stateString 
=  CompressHelp.Compress(statePair);
Page.ClientScript.RegisterHiddenField(PageStateKey, stateString);
}
}
}

//CompressHelp

代码
public   class  CompressHelp
{
// 序列化工具, LosFormatter 是页面默认的序列器
private   static  LosFormatter _formatter  =   new  LosFormatter();
///   <summary>
///  解压并反序列化状态内容
///   </summary>
///   <param name="stateString"> 从客户端取回的页面状态字符串 </param>
///   <returns> 还原后的页面状态Pair 对象 </returns>
public   static   object  Decompress( string  stateString)
{
byte [] buffer  =  Convert.FromBase64String(stateString);
MemoryStream ms 
=   new  MemoryStream(buffer);
GZipStream zipStream 
=   new  GZipStream(ms,
CompressionMode.Decompress);
MemoryStream msReader 
=   new  MemoryStream();
buffer 
=   new   byte [ 0x1000 ];
while  ( true )
{
int  read  =  zipStream.Read(buffer,  0 , buffer.Length);
if  (read  <=   0 )
{
break ;
}m
sReader.Write(buffer, 
0 , read);
} zipStream.Close();
ms.Close();
msReader.Position 
=   0 ;
buffer 
=  msReader.ToArray();
stateString 
=  Convert.ToBase64String(buffer);
return  _formatter.Deserialize(stateString);
}
/
//  <summary>
///  序列化并压缩状态内容
///   </summary>
///   <param name="state"> 页面状态 </param>
///   <returns> 结果字符串 </returns>
public   static   string  Compress( object  state)
{
StringWriter writer 
=   new  StringWriter();
_formatter.Serialize(writer, state);
string  stateString  =  writer.ToString();
writer.Close();
byte [] buffer  =  Convert.FromBase64String(stateString);
MemoryStream ms 
=   new  MemoryStream();
GZipStream zipStream
= new  GZipStream(ms,CompressionMode.Compress, true );
zipStream.Write(buffer, 
0 , buffer.Length);
zipStream.Close();
buffer 
=   new   byte [ms.Length];
ms.Position 
=   0 ;
ms.Read(buffer, 
0 , buffer.Length);
ms.Close();
stateString 
=  Convert.ToBase64String(buffer);
return  stateString;
}
}

 //

代码
protected   override  PageStatePersister PageStatePersister
{
get
{
return   new  CompressPageStatePersister( this );
}
}

 

你可能感兴趣的:(Stream)