Tuesday, 20 August 2013

Clear cookie value and recreate the new cookie

Clear cookie value and recreate the new cookie

I am using the below code to delete the old cookie and create a new
cookie. Error here HttpContext.Current.Request.Cookies[name] having old
cookie value in first load. if i refresh the page means it set new cookie
public void Set_Cookie(string name, string value, ref string retmsg)
{
string str_retval = string.Empty;
try
{
//Delete Old Cookie
if (HttpContext.Current.Request.Cookies[name] == null)
return;
var mycookie = new HttpCookie(name) { Expires =
DateTime.Now.AddDays(-1d) };
HttpContext.Current.Response.Cookies.Add(mycookie);
//Create New Cookie
HttpCookie cookie = new HttpCookie(name);
cookie.Values.Add(name, value.Trim());
HttpContext.Current.Response.Cookies.Add(cookie);
if (HttpContext.Current.Request.Cookies[name] != null)
{
//Error here HttpContext.Current.Request.Cookies[name] having old cookie
value in first load. if i refresh the page means it set new cookie
//HttpCookie cookie_value =
HttpContext.Current.Request.Cookies[name];
if
(HttpContext.Current.Request.Cookies[name].Values[name]
== value.Trim())
{
retmsg = "true";
}
else
{
retmsg = "Invalid Details.Please Try Again.";
}
}
else
{
retmsg = "Invalid Details";
}
}
catch (Exception ex)
{
throw;
}
}

No comments:

Post a Comment