Reputation: 2805
I will use many times a collection that I have in my database, I want to store it in a Session variable so I will not need to read the database every time that I want to have access to that collection(I accept suggestions if you have a better idea to do this instead of using a session variable). In Asp.Net MVC it was pretty easy, just assign the collection to the variable, but in ASP.net Core MVC even if I'm working with the .net Framework is different, I made the configurations that I needed to do in Startup.cs
already, the problem is that Session in ASP.net Core only have implemented these methods(this is an example taken from here):
public IActionResult Index()
{
HttpContext.Session.SetString("Name", "Mike");
HttpContext.Session.SetInt32("Age", 21);
return View();
}
They show you an example of how to implement an extension method to store boolean
types in a Session
variable. But what if I want to store a collection? How could I do that? Let's say that I have a table called Person
with fields like name
, age
, etc. and I want to store a collection of Person
objects in a Session variable, how could I do that?
Upvotes: 0
Views: 5191
Reputation: 20037
If you want to store complex object in Session then you can do like this-
public static class SessionExtensions
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
To store complex object, you can do like this-
var obj= new ComplexClass();
HttpContext.Session.SetObjectAsJson("SessionVariable1", obj);
And read back like this-
var obj= HttpContext.Session.GetObjectFromJson<ComplexClass>("SessionVariable1");
See if this helps.
Upvotes: 4
Reputation: 16815
For application-wide caching (same values for all users) use Caching, for example MemoryCaching
Upvotes: 2