简体   繁体   中英

Store a collection in a session Asp.net Core .net Framework

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?

对于应用程序范围的缓存(所有用户使用相同的值),请使用缓存,例如MemoryCaching

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM