asp.net-mvcserializationsession-state-server

ASP.NET MVC 3 - custom Profile and persisting in State Server


We have a custom profile class inheriting from ProfileBase. We'd like to pop this object into Session to remove the need to keep retrieving it per request.

We're using ASP.NET State Server and we're hitting the following exception:

Type 'ProfileCommon' in Assembly 'App_Code.nvrow7px, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Adding Serializable to our class didn't help. I assume the "ProfileCommon" in the message is a bit of red herring as that's not the name of our class but it is the nmae when you use Profiles with Web Projects.

Is the only option to translate our custom Profile object to a serializable type for "transport" in and out of Session?

Cheers


Solution

  • The ASP.NET StateServer uses binary serialization to store any object graphs. Binary serialization requires that every object within the object graph be serializable (including object basetypes). As such marking just your custom profile class as [Serializable] will do little if the classes in its class hierarchy do not also implement [Serializable]

    Neither ProfileBase nor ProfileCommon implement [Serializable] as such it's not possible to store any class deriving from them within the StateServer without either copying this data over to a fully serializable class hierarchy or transforming the data into another format (e.g. XML) and serializing this.

    For further information:

    Objects stored in session state must be serializable if the mode is set to StateServer. For information on serializable objects, see the SerializableAttribute class.

    Session State-Modes

    Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.

    SerializableAttribute