2008-10-13 30 views

回答

30

如果你想在運行時獲取會話的大小,而不是在調試跟蹤,你可能想嘗試這樣的事:

long totalSessionBytes = 0; 
BinaryFormatter b = new BinaryFormatter(); 
MemoryStream m; 
foreach(var obj in Session) 
{ 
    m = new MemoryStream(); 
    b.Serialize(m, obj); 
    totalSessionBytes += m.Length; 
} 

(由http://www.codeproject.com/KB/session/exploresessionandcache.aspx啓發)

+0

謝謝。那是我需要的。 – GrZeCh 2008-10-13 18:34:51

+1

我需要進行以下更改: long totalSessionBytes = 0; 因爲m.Length返回一個長。但除此之外,這是一段精美的簡潔代碼!循環也可以是foreach。 ;-) – Oliver 2010-07-16 21:56:10

0

我想你可以通過在aspx頁面的頁面指令中添加Trace =「true」來找到該信息。然後,當頁面加載時,您可以看到大量關於頁面請求的詳細信息,包括我認爲的會話信息。

您還可以通過向web.config文件添加一行來在整個應用程序中啓用跟蹤。喜歡的東西:

<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime" 
localOnly="true"/> 
16

上面的答案中的代碼不斷給我相同的數字。這裏是最後爲我工作的代碼:

private void ShowSessionSize() 
{ 
    Page.Trace.Write("Session Trace Info"); 

    long totalSessionBytes = 0; 
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = 
     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
    System.IO.MemoryStream m; 
    foreach (string key in Session) 
    { 
     var obj = Session[key]; 
     m = new System.IO.MemoryStream(); 
     b.Serialize(m, obj); 
     totalSessionBytes += m.Length; 

     Page.Trace.Write(String.Format("{0}: {1:n} kb", key, m.Length/1024)); 
    } 

    Page.Trace.Write(String.Format("Total Size of Session Data: {0:n} kb", 
     totalSessionBytes/1024)); 
} 
相關問題