ASP.NET: Compress ViewState

前端 未结 8 929
礼貌的吻别
礼貌的吻别 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:03

    Again, after some research into this I summarized my findings in a blog-post about Compressing View State.

    To save a compressed View State, this is what I did:

    protected override void SavePageStateToPersistenceMedium(object state) {
        SaveCompressedPageState(state);
    }
    
    private void SaveCompressedPageState(object state) {
        byte[] viewStateBytes;
        using(MemoryStream stream = new MemoryStream()) {
            ObjectStateFormatter formatter = new ObjectStateFormatter();
            formatter.Serialize(stream, state);
            viewStateBytes = stream.ToArray();
        }
    
        byte[] compressed = CompressionHelper.Compress(viewStateBytes);
        string compressedBase64 = Convert.ToBase64String(compressed);
    
        ClientScript.RegisterHiddenField(ViewStateFieldName, compressedBase64);
    }
    

    And for the loading-part, this code made it work for me:

    protected override object LoadPageStateFromPersistenceMedium() {
        return LoadCompressedPageState();
    }
    
    private object LoadCompressedPageState() {
        string viewState = Request.Form[ViewStateFieldName];
        if(string.IsNullOrEmpty(viewState)) {
            return string.Empty;
        }
    
        byte[] decompressed = CompressionHelper.Decompress(viewState);
        string decompressedBase64 = Convert.ToBase64String(decompressed);
    
        ObjectStateFormatter formatter = new ObjectStateFormatter();
        return formatter.Deserialize(decompressedBase64);
    }
    

提交回复
热议问题