2008-10-13 31 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)); 
} 
相关问题