views:

118

answers:

1

I am storing an array of a custom serializable class in session on my site. When a page on the site changes, suddenly it renders them invalid, and tells me that it can't cast the type to it's own type. I assume the class version numbers are changing or something?!

I'd appreciate avoiding the "don't use session" answers, unless it's a really simple solution. I'm not trying to redesign this whole process.

Unable to cast object of type 'ShipmentPackages[]' to type 'ShipmentPackages[]'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidCastException: Unable to cast object of type 'ShipmentPackages[]' to type 'ShipmentPackages[]'.

Source Error: 


Line 21:         Else
Line 22:             If Not Session("ShipmentList") Is Nothing Then
Line 23:                 ShipmentList = DirectCast(Session("ShipmentList"), ShipmentPackages()).ToList
Line 24:             End If
Line 25:         End If
+1  A: 

I have seen this message a number of times myself, it is very annoying! As you pointed out, it probably because the assembly version changed. In Asp.Net, when the page changes, the code gets recompiled. Depending on where you put the class will determine if the class gets recompiled with the page or not. I would suggest moving any "model" type classes to a separate project. This will avoid this problem as well as the urge to mix view/controller and model code :).

You can also try serializing the object into session as XML. If you do, you should be able to deserialize it even if the assembly changes, though not if the properties on the object change.

I know you said you didn't want to hear this, but you might also consider not putting objects in the session. This makes it difficult to scale your application if the time ever comes that it is necessary. The sooner you fix this the easier it will be to fix.

Brian