I am writing an ASP.NET 5 MVC 6 (Core) application. Now I came to a point where I need to store (set and get) an object in the session-cache (ISession
).
As you may know, the Set
-method of ISession
takes a byte-array
and the Get
-method returns one.
In a non-core-application I would use the BinaryFormatter
to convert my object. But how can I do it in a core-application?
Under the hood, Session is built on top of IDistributedCache, which can be used as a more generalised cache in your application. ASP.NET Core ships with a number of IDistributedCache implementations, the simplest of which is an in-memory implementation, MemoryCache, which can be found in the Microsoft.Extensions.Caching.Memory package.
ASP.NET Core session objects store byte array to ensure that session values are serializable, as ASP.NET Core does not perform any operation such as serialization/deserialization on the values stored in the session. Unlike, the traditional ASP.NET session API allows you to set a session value by assigning any type to a session key.
Session in ASP.NET Core. ASP.NET Core supports the concept of a Session out of the box - the HttpContext object contains a Session property of type ISession. The get and set portion of the interface is shown below (see the full interface here):
Keep the cache in sliding expiration mode, so that each time it is read it revives the expiry time - thereby keeping the objects in cache as long as the session is active. Second point alone is not enough, you will need to implement heartbeat technique - triggering the call to session every T minus 1 min or so from the javascript.
I'd go with serializing the objects to JSON and use the extensions methods on ISession
to save them as string
's.
// Save var key = "my-key"; var str = JsonConvert.SerializeObject(obj); context.Session.SetString(key, str); // Retrieve var str = context.Session.GetString(key); var obj = JsonConvert.DeserializeObject<MyType>(str);
The extension methods on ISession
are defined in the Microsoft.AspNet(Core).Http
namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With