0

I have tried the following but, the cookie is not expired after the given time. Can you please look into my code

System.Web.HttpCookie currentUserCookie = System.Web.HttpContext.Current.Request.Cookies["Userdata"];
System.Web.HttpContext.Current.Response.Cookies.Remove("Userdata");
currentUserCookie.Expires = DateTime.Now.AddMinutes(10);

Can anyone help me?

1 Answers1

4

You'll need to use the Response object to write back to the browser:

if ( Request.Cookies["MyCookie"] != null )
{
    var c = new HttpCookie( "MyCookie" );
    c.Expires = DateTime.Now.AddDays( -1 );
    Response.Cookies.Add( c );
}

More information on MSDN: https://msdn.microsoft.com/en-us/library/ms178195.aspx

XamDev
  • 3,377
  • 12
  • 58
  • 97
  • i want to clear cookie after 10 minutes. how can i use this ? –  Mar 23 '17 at 04:22
  • or can we set expire time to zero aftre the cookie expired –  Mar 23 '17 at 04:29
  • @RahulBridge, that's what the Cookie.Expires do, you can set whatever expiration time you want to set. See this http://stackoverflow.com/questions/5122404/how-do-you-clear-cookies-using-asp-net-mvc-3-and-c – XamDev Mar 23 '17 at 04:39
  • after clearing cookies im getting like this Domain: null Expires: {0001-01-01 00:00:00} HasKeys: false HttpOnly: false Name: "Userdata" Path: "/" Secure: false Shareable: false Value: "" Values: {} I need to check if the cookie is expired i want to return null . So how can i check that ?? if iam clearing cookie –  Mar 23 '17 at 04:49
  • is there any way to set null in the "Expires" to null when the cookie is expired. so i can check with this value –  Mar 23 '17 at 04:51
  • you can check whether cookie is null OR not like `if (controller.HttpContext.Request.Cookies[cookieName] == null) return;` – XamDev Mar 23 '17 at 04:59
  • cookie automatically expires on page load. how can i prevent that ? –  Mar 23 '17 at 05:42
  • @RahulBridge Means I didn't get you ? – XamDev Mar 23 '17 at 05:48
  • if i set 5 mins to cookie, it will showing that cookie will expires Expires: {3/23/2017 11:28:23 AM}. but after that on page load Expires: {0001-01-01 00:00:00}. This is the problem –  Mar 23 '17 at 05:53
  • 1
    you should add the cookie in HttpResponse object while creating it, if not obviously you will not get it. it doesn't matter how many times you load the page within that stipulated time, only on load you should check whether cookie is null OR not else create a new cookie – XamDev Mar 23 '17 at 05:56