Dan Lugg
Dan Lugg

Reputation: 20592

Casting objects from session in ASP.NET C#

Preamble: I'm working in a legacy environment ASP.NET/.NET 2.0, without Visual Studio. Notepad++ and FTP at the moment. While hardly ideal, this is the hand I'm dealt at the moment. I have no direct/immediate control over the IIS instance, or the server machine at the moment.


I store an object, of type Foo in session:

this.Session["foo"] = new Foo();
this.Response.Redirect("the/second/page");

On the second page, I retrieve from session, and attempt to cast it for use:

Foo foo = (Foo) this.Session["foo"];

And I recieve:

System.InvalidCastException: Unable to cast object of type 'Foo' to type 'Foo'.

When I compare the type names via .GetType() on the second page:

Foo in session:      ASP._dev_blah_aspx+Foo  
New instance of Foo: ASP._dev_blah_aspx+Foo

However their type GUIDs via .GetType().GUID are different:

Foo in session:      a67f218d-...
New instance of Foo: 267f20ea-...

Does this perhaps have anything to do with this question/answer? I'd try, but refer to preamble.

Upvotes: 0

Views: 2727

Answers (2)

iamkrillin
iamkrillin

Reputation: 6876

Another way you can prevent this from happening is by always precompiling your site prior to uploading it (use the publish option from within visual studio)

Upvotes: 0

System Down
System Down

Reputation: 6260

When you upload your code, try to force a recompile. Easiest way to do this is to touch you web.config. Just open it up with Notepad++ and add a space anywhere, so that the server recognizes that it has changed.

Upvotes: 1

Related Questions