Non-Serializable Object Stored in Session
Summary
The method Reset() in Random.aspx.cs stores a non-serializable object as an HttpSessionState
attribute on line 65, which can damage application reliability.Storing a non-serializable object as an HttpSessionState
attribute can damage application reliability.
Explanation
By default, ASP.NET servers store the HttpSessionState
object, its attributes and any objects they reference in memory. This model limits active session state to what can be accommodated by the system memory of a single machine. In order to expand capacity beyond these limitations, servers are frequently configured to persistent session state information, which both expands capacity and permits the replication across multiple machines to improve overall performance. In order to persist its session state, the server must serialize the HttpSessionState
object, which requires that all objects stored in it be serializable.
In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable]
attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable
interface.

Example 1: The following class adds itself to the session, but since it is not serializable, the session cannot be serialized correctly.

Recommendation
In many cases, the easiest way to fix this problem is to have the offending object declare the [Serializable]
attribute. If the class requires custom serialization and deserialization methods, it must also implement the ISerializable
interface.
Example 2: The code in Example 1 could be rewritten in the following way:
using System.Web;namespace glob{[Serializable]
public class DataGlob {
String GlobName;
String GlobValue;public void AddToSession(HttpSessionState session) {
session["glob"] = this;
}
}}
Generally, implementing a serializable class is straightforward. However, some types of objects will require special treatment. Watch out for objects that hold references to external resources, such as streams and pointers, which are likely to cause complications.
Note that for complex objects, the transitive closure of the objects stored in the session must be serializable. For example, if object A references object B and object A is stored in the session, then both A and B must declare the [Serializable]
attribute and implement any necessary serialization or deserialization methods