简体   繁体   中英

How to clear particular cache value in c#?

I am storing a user name into cache["sKey"] in login page if this cache variable is empty then will go to login page.But after log out have to clear this object data.I tried with below.

public void empLogin()
        {
            try
            {
string sKey = txtUName.Text + txtPwd.Text;
                            string sUser = Convert.ToString(Cache[sKey]);

                            if (sUser == null || sUser == String.Empty)
                            {
                                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                                HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut,
                                System.Web.Caching.CacheItemPriority.NotRemovable, null);
Session["user"] = txtUName.Text + txtPwd.Text;
if (userType == "Admin")
{
  Response.Redirect("~/Admin/DashBoard.aspx");
}
 }
else
   {
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('This User Alredy logged in');", true);
   }

in logut button click.

protected void linkLogout_Click(object sender, EventArgs e)
{
  Cache["sKey"] = string.Empty;
  Response.Redirect("~/LoginPage.aspx");
}

the simplest way is to use:

protected void linkLogout_Click(object sender, EventArgs e)
{
  if(Cache["sKey"] != null)
        Cache.Remove("sKey");
  Response.Redirect("~/LoginPage.aspx");
}

change Cache.Insert as below

 HttpContext.Current.Cache.Insert("sKey", sKey, null, DateTime.MaxValue, SessTimeOut,System.Web.Caching.CacheItemPriority.NotRemovable, null);

current problem is your Cache key name is not "sKey" it is combination of txtUName.Text and txtPwd.Text

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