20

How to find out size of session in ASP.NET from web application?

dove
  • 20,469
  • 14
  • 82
  • 108
GrZeCh
  • 2,332
  • 8
  • 29
  • 38

4 Answers4

31

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)

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
ddc0660
  • 4,022
  • 2
  • 21
  • 30
  • 1
    I needed to make the following changes: long totalSessionBytes = 0; since m.Length returns a long. But aside from that it's a nice concise piece of code! The loop can be foreach, as well. ;-) – Oliver Jul 16 '10 at 21:56
  • @Oliver Thanks for the feedback. I made the adjustments you suggested. Looks a little nicer now. – ddc0660 Jul 22 '10 at 20:49
  • This can't be right. I've got 793 coming back, which seems extremely low. – Ajit Goel Feb 18 '16 at 18:41
  • @dlatikay Your edit is likely to be rejected even though it fixes a bug. You should consider writing a new answer with your changes. – Cave Johnson Dec 12 '16 at 20:08
  • ok, understood. am not that firm in SO policy yet when it comes to fix accepted answers that are wrong (see previous comments here). will do depending on eventual outcome of review. – Cee McSharpface Dec 12 '16 at 20:11
  • @Trikaldarshi, @markthewizard1234 and @Ajit you're correct this is not quite the solution. it retrieved the sum of the lengths of the session *keys*, because that's what the enumerator of the HttpSession collection returns when we do foreach(var obj in Session). If we make it `foreach(string key in Session) { var obj=Session[key]; ... }` it will work fine. Add a null check if session slots can contain nulls. – Cee McSharpface Dec 12 '16 at 20:18
  • The value produced by the code in this answer is meaningless because Session state doesn't necessarily use BinaryFormatter Serialization (`InProc` doesn't serialize at all) and serialization formats introduce their own overheads. The actual memory usage of session-state is highly context dependent (e.g. struct packing). The only way to get a "real" answer is by using a Memory Profiling tool. – Dai May 21 '18 at 07:25
  • Sorry, but this solution will give the size of the session-key, not value? `obj` in the foreach is the key. – cederlof Oct 16 '20 at 08:25
  • The size of the keys is only of marginal utility. For example, I have 20K records in a hashtable, each is 47 bytes (or so). These are parked in the session (right or wrong) and the total is only 115 ( totalSessionBytes ). Doesn't really help figure out if this approach to maintainingg a hashtable for a user session is a looming disaster – Allen Mar 03 '22 at 17:16
24

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));
}
David
  • 291
  • 3
  • 2
  • 1
    You should add a check to make sure the object is not null before trying to serialize. – kheld Jan 13 '14 at 19:05
  • I do not want to be petty, but the size is actually in kB (kilobytes), not kb (kilobits) :-) – Mikee Jan 30 '14 at 12:33
  • So why is this not the right answer? Please explain. I – Allen Mar 03 '22 at 17:18
  • yes, test for null, and add this to make sure the object in question is in fact serializable: https://stackoverflow.com/questions/81674/how-to-check-if-an-object-is-serializable-in-c-sharp – Allen Mar 03 '22 at 17:44
0

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"/>
Rafe
  • 8,467
  • 8
  • 47
  • 67
0

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
cederlof
  • 7,206
  • 4
  • 45
  • 62