0

I have a user control and I want to cache it as long as session does not change.

 <%@ OutputCache Duration="18000"  VaryByParam="none" VaryByCustom="changeIt" %>

Now it should cache as long as Session["UserId"] does not change but when session values changes(or even session becomes null) it should clear cache and again maintain until session changes. TIA.

I have tried below code in global file but not getting the logic(how to compare current and previous session values):

 public override string GetVaryByCustomString(HttpContext ctx, string custom)
        {
            string name = System.Web.HttpContext.Current.Cache["KeyName"] as string;
            if (custom == "changeIt")
            {                  
                string lastSessionVal = "", currentSessionVal = "";
                if (Session["Last_BusinessID"] != null)
                {
                    lastSessionVal = Convert.ToString(Session["Last_BusinessID"]);
                }
                if (System.Web.HttpContext.Current.Session["GSID"] != null)
                    currentSessionVal = Convert.ToString(System.Web.HttpContext.Current.Session["GSID"]);
                else if (System.Web.HttpContext.Current.Session["PLID"] != null)
                    currentSessionVal = Convert.ToString(System.Web.HttpContext.Current.Session["PLID"]);
                else
                {
                    Session.Abandon();
                    Session.Clear();
                    string webaurl = ConfigurationManager.AppSettings["weburl"];
                    Response.Redirect(webaurl + "gs/business-provider-login");
                }
                Session["Last_BusinessID"] = currentSessionVal;
                if (lastSessionVal != currentSessionVal)
                {
                    Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //Response.Cache.SetNoStore();
                    Session["ReloadLeftMenus"] = "1";
                }
                else { Session["ReloadLeftMenus"] = null; }
                return Guid.NewGuid().ToString();
            }
            return base.GetVaryByCustomString(ctx, custom);
        }

Till now its working fine, but I want to cache again when new session value changed and it should be cached until session value changes again.

Sunil Chaudhry
  • 263
  • 5
  • 22

0 Answers0