ViewState 数据太大影响性能导致页面报错

案件背景:

工作中的一个报表之前一直工作正常,但是有一天突然用户打开报错,提示view state 无效。检查代码发现没有问题,检查前台页面后发现报表显示后的viewstate大小居然达到40M以上。

通过在页面增加下面两个事件的代码,把view state 保存到文本文件中。可以让页面显示速度大大提高。

VB.NET 版
    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal state As Object)
        Dim x As New ObjectStateFormatter()
        Dim value As String = x.Serialize(state)
        Dim viewStateID As String = DateTime.Now.Ticks + Me.GetHashCode().ToString
        Dim fn As String = System.IO.Path.Combine(Request.PhysicalApplicationPath, "App_Data/ViewState/" + viewStateID)
        System.IO.File.WriteAllText(fn, value)
        Cache.Insert(viewStateID, value)
        MyBase.SavePageStateToPersistenceMedium(viewStateID)
    End Sub

    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Dim viewStateID As String
        viewStateID = CType(MyBase.LoadPageStateFromPersistenceMedium, Pair).Second.ToString
        Dim stateStr As String = ""
        Dim result As New Object
        If Cache(viewStateID) IsNot Nothing Then
            stateStr = Cache(viewStateID).ToString()
        End If


        If stateStr.ToString.Equals("") = False Then
            Dim fn As String = System.IO.Path.Combine(Request.PhysicalApplicationPath, "App_Data/ViewState/" + viewStateID)
            stateStr = System.IO.File.ReadAllText(fn)
        End If
        Dim x As New ObjectStateFormatter()
        If stateStr.Equals("") = False Then
            result = x.Deserialize(stateStr)
        End If
        Return result


    End Function
C# 版
    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal state As Object)

        string value = new ObjectStateFormatter().Serialize(state);
        string viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码
        string fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
        //ThreadPool.QueueUserWorkItem(File.WriteAllText(fn, value));
        File.WriteAllText(fn, value); 
        Cache.Insert(viewStateID, value);
        base.SavePageStateToPersistenceMedium(viewStateID);

    End Sub


你可能感兴趣的:(ViewState 数据太大影响性能导致页面报错)