Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 (Core): How to store objects in session-cache (ISession)?

Tags:

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?

like image 491
evaenrique Avatar asked Mar 14 '16 16:03

evaenrique


People also ask

What is session cache in ASP NET Core?

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.

What is a session object in ASP NET Core?

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.

What is iSession in ASP NET Core?

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):

How to keep objects in cache when session is active?

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.


1 Answers

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.

like image 175
Henk Mollema Avatar answered Dec 30 '22 15:12

Henk Mollema