Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

How can I find which object in ASP.NET can't be serialized?

I'm getting the following error in my application:

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

The stack trace isn't providing any good information on which object is not able to serialize. Is there a good way to find the problem child?

Edit: I've found the issue, I was trying to serialize a Linq statement(not executed). But I'll try an choose an answer that would have best solved this issue.

Upvotes: 6

Views: 2055

Answers (5)

Protector one
Protector one

Reputation: 7271

You can try to serialize the object, and inspect the System.Runtime.Serialization.SerializationException that's thrown when it's not serializable. It should tell you which member or parent of the object can't be serialized.

Example code:

var f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
f.Serialize(new System.IO.MemoryStream(), yourObject);

Upvotes: 2

phabtar
phabtar

Reputation: 1149

You can find the culprit types which fire the serialization exception through .net framework code debugging. At least that's what I did.

Upvotes: 0

Wyatt Barnett
Wyatt Barnett

Reputation: 15663

MbUnit (now Gallio) has an Assert.IsSerializable() test that could come in handy here.

Upvotes: 2

mfeingold
mfeingold

Reputation: 7152

The best I could do in a similar situation is to look at every object the Session references and check it for the presence of the Serializable attribute (or that the object implements ISerialzable interface).

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063393

Really, you should mainly be storing your own state data / objects (ideally modelled as DTO classes), in which case the answer is: any you mark as [Serializable] or ISerializable. You shouldn't be adding raw UI controls or other unknown objects to session-state. In particular, for reasons like this, which had a major performance impact on an app the other day.

Upvotes: 5

Related Questions