How can I delete a cookie in a particular page? - asp.net

I am creating a cookie in one page of an ASP.NET application and I want to delete it in another page. How do I do that?

Microsoft: How To Delete a Cookie
You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
To assign a past expiration date on a cookie
Determine whether the cookie exists in the request, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object of the Response.
The following code example shows how to set a past expiration date on a cookie.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Note: Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.

Have you tried expiring your cookie?
protected void btnDelete_Click(object sender, EventArgs e)
{
Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1);
}

How to: Delete a Cookie
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("MyCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}

First you have to set the expiry date of the cookie to a previous date.
For Example :
HttpCookie newCookie = new HttpCookie("newCookie");
newCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(newCookie);
Now only doing this will not be helpful as the cookie will not be physically removed. You have to remove the cookie.
if (newCookie.Expires < DateTime.Now)
{
Request.Cookies.Remove("newCookie");
}
Here you go. This applies to any page within the solution.

Related

Something wrong with cookies in asp.net

I am building a web application and when a user signs in, his credentials are first validated against the database. If the credentials are correct, a FormsAuthenticationTicket is created. Then a cookie is created from that ticket. The Expires and Path properties are set. See below.
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket(1, model.User.UserName,
DateTime.Now, DateTime.Now.AddHours(2), RememberMeCheckBox.Checked,
model.User.Id.ToString()+" "+model.User.UserType.ToString());
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
cookie.Expires=ticket.Expiration;
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
Response.Redirect("DummyForm.aspx");
And when I redirect the response to a new page, in the Page_Load event the presence of a cookie is checked.
HttpCookie cookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookiePath];
if(cookie!=null)
{
//Do stuff
}
else
{
//Do other stuff
}
When I run the application, it behaves like the cookie variable is null.
Is there something that I have omitted?
Thanks in advance for your help.
cookie.Domain="localhost";
cookie.Name="My auth cookie";
I also set the domain property to localhost in web.config. However, it still doesn't work. I used the developer tools of Google to check the cookie and I can't see it there.

Expiring asp.net session cookie

In my logout function, I have
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
I see that the response contains set-cookie for ASP.NET_SessionId with the proper expiration, but then the browser (Chrome in this case) never actually deletes the cookie.
tiy can try with this code
HttpCookie myCookie = new HttpCookie("ASP.NET_SessionId");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);

asp.net delete cookie

I'm using a cookie containing an encrypted key to use for authentication. What i need is to delete this cookie on logout. As per msdn a cookie cannot be removed from a client's browser, so I tried to set expiry date HttpContext.Current.Request.Cookies["CAuthCookie"].Expires = DateTime.Now.AddDays(-1);, however the cookie remains. Any other ideas?
Try this:(place this in your logout code)
HttpCookie cookie = new HttpCookie("CAuthCookie", "");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(cookie);

Asp.Net 4 Response.Cookies.Add does not add cookie to users machine

I am trying to setup a basic Form Authentication using ASP.NET 4.
I know my validation code (code that checks if the username and password is correct) is working because after if the user enters invalid information the ReturnLable tells them so. However if they enter the correct information, they are redirected to the restricted page with a 403 – Forbidden error. When I check the shell:cookie path no cookie has been written even though I added it to the collection “Response.Cookies.Add(cookie);”
protected void Submit_Click(object sender, EventArgs e)
{
Email.Text = Email.Text.Trim();
Password.Text = Password.Text.Trim();
if (IsValid(Email.Text, Password.Text)) //user exists
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Email.Text,
DateTime.Now,
DateTime.Now.AddMinutes(50),
RememberMe.Checked,
"user",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}
else
{
ReturnLable.Text = "<font color=red> Username/Password Incorrect Please Try Again </font>";
ReturnLable.Visible = true;
}
From this MSDN article:
If you do not set the cookie's expiration, the cookie is created but
it is not stored on the user's hard disk. Instead, the cookie is
maintained as part of the user's session information. When the user
closes the browser or if the session times out, the cookie is
discarded.
Thus, a cookie could be successfully set, alive and well in the browser, but have no corresponding file in the "cookies" folder on the hard drive.
make sure that Enable anonymous access is disabled on IIS and Integrated Windows security is enabled

Get Session to expire gracefully in ASP.NET

I need a way to tell ASP.NET "Kill the current session and start over with a brand new one" before/after a redirect to a page.
Here's what I'm trying to do:
1) Detect when a session is expired in the master page (or Global.asax) of an ASP.NET application.
2) If the session is expired, redirect the user to a page telling them that their session is expired. On this page, it will wait 5 seconds and then redirect the user to the main page of the application, or alternatively they can click a link to get there sooner if they wish.
3) User arrives at main page and begins to use the application again.
Ok, so far I have steps 1 and 2 covered. I have a function that detects session expiry by using the IsNewSession property and the ASP.NET Session ID cookie value. if it detects an expired session it redirects, waits five seconds and then TRIES to go to the main page.
The problem is that when it tries to redirect, it gets to the part in the master page to detect an expired session and it returns true. I've tried calling Session.Abandon(), Session.Clear(), even setting the session to NULL, with no luck.
Someone out there has had to have faced this problem before, so I'm confident in the community to have a good solution. Thanks in advance.
The problem you are describing happens because asp.net is reusing the sessionid, if the sessionid still exists in the auth cookie when you call abandon() it will just reuse it, you need to explicitly create a new sessionid afaik something like:
HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
mycookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(mycookie);
For ASP.NET MVC this is what I'm doing with an action method.
Note:
Returns a simple view with no other resources that might accidentally re-create a session
I return the current time and session id so you can verify the action completed succcessfully
public ActionResult ExpireSession()
{
string sessionId = Session.SessionID;
Session.Abandon();
return new ContentResult()
{
Content = "Session '" + sessionId + "' abandoned at " + DateTime.Now
};
}
The code in your master page, which detects an expired session and redirects, should look like this:
if (Session != null
&& Session.IsNewSession
&& Request.Cookies["ASP.NET_SessionId"] != null
&& Request.Cookies["ASP.NET_SessionId"].Value != "")
{
Session.Clear();
Response.Redirect(timeoutPageUrl);
}
Calling session.Clear() before redirecting ensures that on the subsequent page, Session.IsNewSession will be false.
Also note that I am checking for an empty string in the value of of the ASP.NET_SessionId cookie. This helps to prevent a logout from being mistaken as an expired session, if you happen to call Session.Abandon() in your logout process. In that case, make sure you expire the old session cookie as a part of the logout process:
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.MinValue;
The adding the cookie trick worked for me also, as follows:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
If Session.IsNewSession Then
'If Not IsNothing(Request.Headers("Cookie")) And Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
If Not IsNothing(Request.Headers("Cookie")) AndAlso Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
'VB code
Dim MyCookie As HttpCookie = New HttpCookie("ASP.NET_SessionId")
MyCookie.Expires = System.DateTime.Now.AddDays(-1)
Response.Cookies.Add(MyCookie)
'C# code
'HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
'mycookie.Expires = DateTime.Now.AddDays(-1);
'Response.Cookies.Add(mycookie);
Response.Redirect("/timeout.aspx")
End If
End If
End Sub
Are you calling Session.Abandon in your special "Your session expired" page? If so, don't.

Resources