1

I have a project in web forms and I am trying to convert it into asp.net core. My problem is that in web forms I save an object to the session and when I get it I can make changes on it and it keeps them. On the other hand, in core I set the object to the session by serializing it. When I get it and make changes it doesn't affect the object stored in the session. Is there a way to save the object as it is (without serializing it), so when I get it from the session and make changes on it, to continue using it and don't have to set it in the session again?

The session was

 System.Web.HttpContext.Current.Session["object"]

And made it

AppHttpContext.Current.Session.GetString("object") 

And then i deserialized it to the object i want.

Ps: I used AppHttpContext to get the session outside of a controller

2
  • It is a bit of an X/Y question. You can make sessions work but you should try to avoid that. The rest of your problem is not very clear, what means "without serializing" ?
    – bommelding
    Jan 30, 2019 at 10:24
  • How about a static MemoryCache somewhere. Then use key SessionId and value Dictionary<string, object> as storage for session entries.
    – Charles
    Feb 14, 2022 at 9:30

4 Answers 4

5

For using object/array in session you need some customization:`

public static class SessionExtensions {
public static void SetObject(this ISession session, string key, object value)
{
    session.SetString(key, JsonConvert.SerializeObject(value));
}

public static T GetObject<T>(this ISession session, string key)
{
    var value = session.GetString(key);
    return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
} }

Now you can set it this way:

var objComplex = new ComplexClass();
HttpContext.Session.SetObject("ComplexObject", objNew);

And retrieve it:

var objComplex = HttpContext.Session.GetObject("ComplexObject");
1
  • This work for a lot of different scenarios, but it's not storing a object. You are storing string as a serialized object. What is the difference? You don't have access to object metadata information, for instance, it won't works good if you are using polymorphism.
    – mfvjunior
    Sep 14, 2021 at 19:19
4

Technically, ASP.NET never supported this either. It was a fluke that just happened to work when using InProc (i.e. in memory) sessions, due to the way session storage worked in that case. If you used an alternate session store like SQL Server, you would also have to serialize/deserialize objects in and out of the session. ASP.NET Core differs only in that uses a generalized session store, so it forces any object to be serialized/deserialized, even if you're using an in-memory store.

That said, your issue here is that you're simply not persisting your changes back. Again, you were relying on accidental behavior. Because ASP.NET was directly persisting the object in memory, performing operations on that object automatically "persisted" because it was the same reference. When deserializing, you are creating a new instance, so operations will not persist unless you serialize the object back into the session afterwards.

Finally, Web Forms or no, this was never a recommended or even correct way to do things. Session storage is volatile. It's not intended for anything other than short-term (and unreliable) persistence. In other words, you can never count on something being in the session, so you should always defensively code around the case where the data does not exist. If you're depending on something being there, as it sounds like is the case here, then you were always setting yourself up for failure.

However, if you're doing something like a multi-step form, it's acceptable for the individual steps to go into the session, though you should actually be using TempData rather than Session for that. At the last step, though, your composed object should be persisted in something like SQL Server, not the session. In virtually all other cases, you should simply persist in something like SQL Server, and avoid Session entirely.

1

The migration task is not going to be straightforward.

You can follow these steps:

  1. First replace your dependency on Session on some kind of Service that you can inject into controllers or other services. A good idea would be to hard code values in this service to check if all code depending on your earlier session implementation is able to use the new Service.

  2. Implement a Filter (for example by implementing IAsyncPageFilter in case of Razor pages) to tap into the HttpContext User and setup some kind of Lookup object that can be retrieved from a Cache implementation - A good idea would be to use a Redis distributed cache. This object should have the Key as the user identity - values can be whatever data you may want to add to a "session". Use a "Cache" service to implement this, hiding Cache implementation details from Client code. (Remember to make these "Request" scope dependencies so that the HttpContext User is appropriately populated.)

  3. Implement methods on a new Service to add / modify the Cache object to keep your "session" data updated.

Moral of the story: Reduce dependency on platform specific features. At least encapsulate these dependencies using some kind of service that can be replaced later without client code depending on these features.

0

ASP.NET core does not support directly saving objects into Session the way that Web Forms projects can. In ASP.NET Core there is only direct support for saving primitive types into Session like a string, int or byte array. So any more complex object will need to be serialized into a string or serialized directly into a byte array, and that serialization can then be stored in Session.

It's common for people to accomplish this by doing JSON serialization of the object to generate a string and then saving the string into Session. But when you retrieve the JSON string from Session and deserialize it back into an object, any changes to that object won't be reflected in the prior JSON that represented the object which is currently stored in the session. So the changes to the object are not directly reflected in Session.

This is very different behavior than what was seen in Web Forms and results from the fact that the object is not stored in session, it's serialization is. So if you change the object and want those changes stored in session, you will need to serialize the object again and store that serialization (e.g. json) in session.

Does that Help?

5
  • Yes, but what is the alternative to accomplish the above scenario?
    – Mike Komos
    Jan 30, 2019 at 14:19
  • This no alternative if you want to use the Session facilities provided by ASP.NET Core. I suppose you could say the alternative is to write custom session support. I did that for example to be able to store my session in Sql Server with optimistic locking support at the session key level but I don't think most people using ASP.NET Core are writing their own custom session support. :-)
    – RonC
    Jan 30, 2019 at 14:26
  • what about long or datetime primitive types. looks anything other than string, int and byte you will have to serialize and store
    – LP13
    Aug 23, 2021 at 15:08
  • @LP13 There may be 3rd party extension methods in the .NET ecosystem for that but the available extensions methods from Microsoft for the Session object don't include support for long or datetime, see docs here Don't forget to upvote my answer if it was helpful.
    – RonC
    Aug 23, 2021 at 15:29
  • Understood. But not sure why Microsoft has decided to ignore other primitive types. Typically you put stuff in session that you want to read/write on every request. Serializing/DeSerializing primitive types for each request is unnecessary overhead
    – LP13
    Aug 23, 2021 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.