ASP.NET: Compress ViewState

前端 未结 8 932
礼貌的吻别
礼貌的吻别 2021-02-06 00:27

What are the latest and greatest ways to compress the ASP.NET ViewState content?

What about the performance of this? Is it worth it to keep the pages quick and minimize

相关标签:
8条回答
  • 2021-02-06 01:23

    The simple answer might not be what you want to hear. Too often, controls on the page have viewstate by default when they really don't need it. It's a good idea to switch off viewstate until you know you're going to need it, and only switch it on for the (hopefully) few cases where you actually want to keep the view state.

    0 讨论(0)
  • 2021-02-06 01:28
    1. Avoid using ViewState
    2. Use compression on the IIS server.
    3. You can wireup something that will compress the viewstate into and out of a page by doing something like:
    public abstract class PageBase : System.Web.UI.Page
    {
        private ObjectStateFormatter _formatter = new ObjectStateFormatter();
    
        private static byte[] Compress( byte[] data )
        {
                var compressedData = new MemoryStream();
                var compressStream = new GZipStream(output, CompressionMode.Compress, true);
                compressStream.Write(data, 0, data.Length);
                compressStream.Close();
                return compressedData.ToArray();
        }
        private static byte[] Uncompress( byte[] data )
        {
                var compressedData = new MemoryStream();
                input.Write(compressedData, 0, compressedData.Length);
                input.Position = 0;
                var compressStream = new GZipStream(compressedData, CompressionMode.Decompress, true);
                var uncompressedData = new MemoryStream();
                var buffer = new byte[64];
                var read = compressStream.Read(buffer, 0, buffer.Length);
    
                while (read > 0)
                {
                    uncompressedData.Write(buffer, 0, read);
                    read = compressStream.Read(buffer, 0, buffer.Length);
                }
                compressStream.Close();
                return uncompressedData.ToArray();
        }
        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            var ms = new MemoryStream();
            _formatter.Serialize(ms, viewState);
            var viewStateBytes = ms.ToArray();
            ClientScript.RegisterHiddenField("__COMPRESSED_VIEWSTATE"
                , Convert.ToBase64String( Compress(viewStateArray)) );
        }
        protected override object LoadPageStateFromPersistenceMedium()
        {
            var compressedViewState = Request.Form["__COMPRESSED_VIEWSTATE"];
            var bytes = Uncompress( Convert.FromBase64String( compressedViewState ) );
            return _formatter.Deserialize( Convert.ToBase64String( bytes ) );
        }
    }
    
    0 讨论(0)
提交回复
热议问题