Save/Retrieve Session ASP.Net Core MVC

Save/Retrieve Session ASP.Net Core MVC

Session

Plays a vital role while dealing with caching in your browser. ASP.Net Core offers Session caching fast and reliable way. Here is the practical example.

Put following code anywhere in common class or Repository, it has two methods Generic in nature Add/Get.

public static void Add<T>(this ISession iSession, string key, T data)
        {
            string serializedData = JsonConvert.SerializeObject(data);
            iSession.SetString(key, serializedData);
        }
        public static T Get<T>(this ISession iSession, string key)
        {
            var data = iSession.GetString(key);
            if (null != data)
                return JsonConvert.DeserializeObject<T>(data);
            return default(T);
        }

Add Method will allow you to cache object in Browser memory and Get method will help to retrieve cached information from Browser’s memory.

Implementation or Call

Following code will help you to cache Session or retrieve session, It can be written in your Controller

//response refers to result that you would like to cache
HttpContext.Session.Add<List<YourClassObject>>("NameOfYourSession", response);

//This method will help your to retrieve existing session cache
var response = HttpContext.Session.Get<List<YourClassObject>>("NameOfYourSession");

Note: You need to extend HttpContext by implementing ControllerBase in your code to get the access for HttpContext object

Leave a Reply

Your email address will not be published.