How to find out size of session in ASP.NET from web application?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you’re trying to get the size of Session during runtime rather than in debug tracing, you might want to try something like this:
long totalSessionBytes = 0;
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
foreach(var obj in Session)
{
m = new MemoryStream();
b.Serialize(m, obj);
totalSessionBytes += m.Length;
}
(Inspired by http://www.codeproject.com/KB/session/exploresessionandcache.aspx)
Method 2
The code in the answer above kept giving me the same number. Here is the code that finally worked for me:
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));
}
Method 3
I think you can find that information by adding Trace=”true” to the page directive of a aspx page. Then when the page loads you can see a large number of details regarding the page request, including session information i think.
You can also enable tracing in your entire application by adding a line to your web.config file. Something like:
<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime" localOnly="true"/>
Method 4
This is my code for getting all current Session variables with its size in kB into a Dictionary.
// <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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0