2013-10-12 61 views
0

我想壓縮ASP.Net 4.0中的viewstate,因此頁面加載速度更快爲繁重的viewstate頁面。壓縮viewstate添加另一個隱藏的字段與__VIEWSTATE相同的ID

但是,當我在瀏覽器中查看頁面源時,發現2個隱藏字段的名稱和ID爲'__VIEWSTATE'。

我的代碼如下。 如何壓縮視圖狀態,但將其存儲在其原始隱藏字段中而不創建另一個重複隱藏字段?

protected override void SavePageStateToPersistenceMedium(object viewState) 
{ 
    byte[] viewStateArray; 
    using (MemoryStream memoryStream = new MemoryStream()) 
    { 
     _objectStateFormatter.Serialize(memoryStream, viewState); 
     viewStateArray = memoryStream.ToArray(); 
    } 
    ClientScript.RegisterHiddenField("__VIEWSTATE", 
       Convert.ToBase64String(GZip.Compress(viewStateArray))); 
} 

enter image description here

回答

0
using System.IO; 
using System.IO.Compression; 
using System.Web.UI; 

公共類PageCompressed:System.Web.UI.Page {

private ObjectStateFormatter _formatter = new ObjectStateFormatter(); 
protected override void SavePageStateToPersistenceMedium(object viewState) 
{ 
    MemoryStream ms = new MemoryStream(); 
    _formatter.Serialize(ms, viewState); 
    byte[] viewStateArray = ms.ToArray(); 
    ClientScript.RegisterHiddenField("__CVIEWSTATE", Convert.ToBase64String(_Compress(viewStateArray))); 
} 
protected override object LoadPageStateFromPersistenceMedium() 
{ 
    string vsString = Request.Form["__CVIEWSTATE"]; 
    byte[] bytes = Convert.FromBase64String(vsString); 
    bytes = _DeCompress(bytes); 
    return _formatter.Deserialize(Convert.ToBase64String(bytes)); 
} 

private byte[] _Compress(byte[] inputBytes) 
{ 
    MemoryStream m = new MemoryStream(); 
    GZipStream zip = new GZipStream(m, CompressionMode.Compress, true); 
    zip.Write(inputBytes, 0, inputBytes.Length); 
    zip.Close(); 
    return m.ToArray(); 
} 
private byte[] _DeCompress(byte[] inputBytes) 
{ 
    MemoryStream m = new MemoryStream(inputBytes); 
    MemoryStream mout = new MemoryStream(); 
    GZipStream zip = new GZipStream(m, CompressionMode.Decompress, true); 
    do 
    { 
     byte[] bBuffer = new byte[4097]; 
     int iRead = zip.Read(bBuffer, 0, bBuffer.Length); 
     if (iRead > 0) 
     { 
      mout.Write(bBuffer, 0, iRead); 
     } 
     else 
     { 
      break; 
     } 
    } while (true); 
    zip.Close(); 
    return mout.ToArray(); 
} 
} 

您可以使用此接口類由它繼承像壓縮的ViewState這在代碼後面的每一頁

 
    public partial class Default : PageCompressed 
相關問題