Session, TempData, Cache Andres Käver, IT Kolledž
Session System.Web.HttpContext.Current.Session Works like ViewBag – you can save anything into it Default lifetime of session is 20 minutes Is persisted over all requests, unlike TempData TempData is valid only for single redirect Typecasting and checking for null values is required 2
Session Lifetime 20 min Web.config, system.web section 3
Session Saving data to session Accessing data from session 4 System.Web.HttpContext.Current.Session["sessionString"] = sessionValue; var myStr = TryCast( System.Web.HttpContext.Current.Session("sessionString"), [String]);
Session - Extension method 5 public static class SessionExtensions { public static T GetDataFromSession ( this HttpSessionStateBase session, string key) { return (T)session[key]; } public static void SetDataToSession ( this HttpSessionStateBase session, string key, object value) { session[key] = value; } Session.SetDataToSession ("key1", sessionValue); var value = Session.GetDataFromSession ("key1");
Session - methods Add Clear Remove RemoveAll, RemoveAt IsNewSession IsReadOnly 6
Cache Is live data really needed? Live data can be really expensive (cpu, database, bandwith, time) In most cases, live data is not needed. Few minutes old data is good enough, but web page that loads few minutes – impossible. After well structured and optimized code – cache can help. 7
Cache - Output OutputCache atribute, with duration parameter Duration is mandatory, time in seconds – for how long will this output stay in cache 8 [OutputCache(Duration=60)] public ActionResult Index() { return View(); }
Cache - Output When to generate new content? When parameters change: 9 [OutputCache(Duration = 60, VaryByParam = "search")] public ActionResult Contact(string search) { return View(); }
Cache - Output When headers change 10 [OutputCache(Duration = 60, VaryByHeader = "Accept-Language")] public ActionResult Contact(string search) { return View(); }
Cache - Output Location – location of cached item Any – stores the output cache on the client’s browser, on the proxy server (or any other server) that participates in the request, or on the server where the request is processed. Default value. Client – stores the output cache on the client’s browser. Downstream – stores the output cache on any cache-capable devices (other than the origin server) that participates in the request. Server – stores the output cache on the Web server. None – turns off the output cache. 11
Cache - Output SqlDependency – set a dependency between the db and the cache. At any time something is changed within the tracked table(s), new instance of the action result will be created in the cache. CacheProfile –make an Output cache profile in the Web.config – so no recompile is needed for cache configuration. 12
Cache - Output 13 <add name="MyCacheProfile" duration="30" varyByParam="id" location="Any" /> …… [OutputCache(CacheProfile = "MyCacheProfile")] public ActionResult Index() { return View(); }
Cache - Data Cache only the data and not the whole page Use “HttpContext.Cache” Only one instance of the Cache class per application domain 14 public ActionResult Index(){ if (System.Web.HttpContext.Current.Cache["time"] == null){ System.Web.HttpContext.Current.Cache["time"] = DateTime.Now; } ViewBag.Time = ((DateTime)System.Web.HttpContext.Current.Cache["time"]).ToString(); return View(); }
Cache - Data 15 public Object Add( string key, Object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback )
Cache - Data Key – the name with which to access item. Value – the object that we store in the cache. Dependencies – used to configure cache dependencies, indicating when object will be removed from the cache. AbsoluteExpiration – configures the time for which object will stay in the cache. SlidingExpiration – sets how much time after the last accessing cached object will expire. To be able to use this configure the AbsoluteExpiration property to Cache.NoAbsoluteExpiration. 16
Cache - Data CacheItemPriority – defines the priority of the cached item – the items with a lower priority will be removed first when the server releases the system memory. The default value is normal. CacheItemRemovedCallback – defines what happens when a data in the cache expires. This property needs an instance of the CacheItemRemovedCallback class. The method that we pass to the CacheItemRemovedCallback constructor should be ‘void’ with the following parameters – string key, Object val, CacheItemRemovedReason reason. 17