如何从Web应用程序中找出ASP.NET中的会话大小?
如果您试图在运行时而不是在调试跟踪中获取Session的大小,您可能想尝试这样的事情:
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)
上面答案中的代码一直给我相同的数字.这是最终为我工作的代码:
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)); }