[英]How to find out size of session in ASP.NET from web application?
如何从 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));
}
我认为您可以通过将Trace="true"添加到 aspx 页面的页面指令来找到该信息。 然后当页面加载时,您可以看到大量有关页面请求的详细信息,包括我认为的会话信息。
您还可以通过在 web.config 文件中添加一行来在整个应用程序中启用跟踪。 就像是:
<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime"
localOnly="true"/>
这是我的代码,用于将所有当前会话变量及其大小(以 kB 为单位)放入字典中。
// <KEY, SIZE(kB)>
var dict = new Dictionary<string, decimal>();
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
foreach(string key in Session.Keys)
{
var obj = Session[key];
if (obj == null)
{
dict.Add(key, -1);
}
else
{
m = new MemoryStream();
b.Serialize(m, obj);
//save the key and size in kB (rounded to two decimals)
dict.Add(key, Math.Round(Convert.ToDecimal(m.Length) / 1024, 2));
}
}
//return dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.