ASP.NET cookie does not expire - asp.net

I'm trying cookies for the first time in ASP. The problem is, the cookie doesn't expire no matter how many ways I write the code.
Making a cookie:
HttpCookie cookie = new HttpCookie("test");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
Checking if it exists:
if (Request.Cookies["test"] != null)
Response.Write("test");
else
Response.Write("no test");
It always shows "test".

Are you doing this in the same request? In that case the old cookie is still present in the request, but will not be in subsequent requests.

You have destry all cookies in client side..
https://learn.microsoft.com/en-us/dotnet/api/system.net.cookie.expired?view=net-6.0
use this code it works for me.
<script>
$(document).ready(function () {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
});
</script>
Remarks:
Expired cookies, if received, should be destroyed by the client application.

Related

Asp.Net - How to expire Cookie

Tried
if (Request.Cookies["IsGuest"] != null)
{
Response.Cookies["IsGuest"].Expires = DateTime.Now.AddDays(-1);
//HttpCookie myCookie = new HttpCookie("IsGuest");
//myCookie.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies.Add(myCookie);
}
string a = Request.Cookies["IsGuest"].Value;
and also tried by commenting uncommented code and uncommenting commented code but
string a = Request.Cookies["IsGuest"].Value;
Always running and Request.Cookies["IsGuest"] is never null
You got the right concept for deleting a cookie programmatically:
HttpCookie myCookie = new HttpCookie("IsGuest");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
However, you missed one point. The above change won't be effective until the postback completes and subsequently user initiates a new request.
MSDN says:
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.
So, the below code illustrates more here::
protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
HttpCookie myCookie = new HttpCookie("IsGuest");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
// this will always be true here as the Request i.e HttpRequest isn't
// modified actually as the postback isn't complete and we are accessing
// the Cookies collection of same request (not a new request)
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie Collection can't be modified without
making a new request";
}
}
// suppose after postback completes,
// user clicks a button to check the cookie,
// which in turn is a new request/postback/....
protected void CheckCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie is present!";
}
else
{
Label1.Text = "No Cookie is present!";
}
}
One last Note::
Calling the Remove method of the Cookies collection removes the cookie 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.
How to Expire a Cookie (on the Client)
I would not reply on ASP.NET Core to remove or expire cookies, as the server-side has very little to do with what happens on the browser. The ASP.NET application & server also has no knowledge of the names of every outdated-cookie, which paths were assigned, if some have already expired, which cookie names are no longer used from an older website, which ones were renamed, which ones are session cookies that need to remain, etc etc.
Cookies are best controlled on the client, which means running JavaScript (unfortunately).
To do that, I recommend you roll your own cookie expiration routine. Below is one I use that removes the top root-path cookies and a sub-path of cookies under the root, starting at the folder from which the script is called from. This generally means most of your cookies are removed. There are some exotic rules as to how browsers remove expired cookies under subpaths that I wont get into. In some cases some subpaths may be missed. But in general, root cookies would all be expired, and any cookies with the same scipts web path and all subpath under it, also expired.
The script below only sets expiration dates on cookies with paths matching the above rules. But the browsers are design to expire cookies under the subpath above as well. Please test in various browser, however, and customize the script as you like. This will NOT delete sessions stored as cookies!
// Get all cookies for this domain but by name-value pairs:
alert('What cookies do I have (name-value)?\r\n ' + document.cookie);
// Get all cookies
var allcookies = document.cookie;
// Splits into multiple cookies
var cookiesArray = allcookies.split(";");
// Loop through each found cookie...
if (cookiesArray && cookiesArray.length >= 0){
for (var i = 0; i < cookiesArray.length; i++) {
var nameString = "";
var pathString = "";
var expiresString = "";
// Strip out all whitespace or formatting from the name-value pair...
var cookieCleaned = cookiesArray[i].replace(/^\s+|\s+$/gm, '').replace(/[\t\n\r]/gm, '')
namePair = cookiesArray[i].split("=");
nameString = namePair[0] + "=; ";// empty the name's value
const earlydate = new Date(0).toUTCString();
expiresString = "expires=" + earlydate;
// DELETE COOKIES using ROOT PATH and SUBPATH
if (namePair[0] !== ""){
// Reset the cookie subpath with new expiration date
// to force the browser cache to delete it.
var pathname = location.pathname.replace(/\/$/,'');
if (pathname !== '') {
pathname = "path=" + pathname + "; ";
document.cookie = nameString + pathname + expiresString;
alert('Final Cookie1:\r\n ' + nameString + pathname + expiresString);
}
// Reset the cookie rootpath, same as above.
document.cookie = nameString + "path=/; " + expiresString;
alert('Final Cookie2:\r\n ' + nameString + "path=/; " + expiresString);
}
}
}
Better you can remove cookie from your list

How can I create persistent cookies in ASP.NET?

I am creating cookies with following lines:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Now how can I make it persistent?
If I visit the same page again after closing the browser, I'm unable to get it back.
Here's how you can do that.
Writing the persistent cookie.
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());
//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
Reading the persistent cookie.
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
//No cookie found or cookie expired.
//Handle the situation here, Redirect the user or simply return;
}
//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
string userId = myCookie.Values["userid"].ToString();
//Yes userId is found. Mission accomplished.
}
Although the accepted answer is correct, it does not state why the original code failed to work.
Bad code from your question:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.
Corrected code:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.
bool persist = true;
var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
cookie.Expires = DateTime.Now.AddMonths(3);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var userData = "store any string values you want inside the ticket
extra than user id that will be encrypted"
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(cookie);
Then you can read this at any time from an ASP.NET page by doing
string userId = null;
if (this.Context.User.Identity.IsAuthenticated)
{
userId = this.Context.User.Identity.Name;
}
As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true
It is the main idea.
bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name,
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
if (isPersisted)
authCookie.Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
You need to add this as the last line...
HttpContext.Current.Response.Cookies.Add(userid);
When you need to read the value of the cookie, you'd use a method similar to this:
string cookieUserID= String.Empty;
try
{
if (HttpContext.Current.Request.Cookies["userid"] != null)
{
cookieUserID = HttpContext.Current.Request.Cookies["userid"];
}
}
catch (Exception ex)
{
//handle error
}
return cookieUserID;
//add cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//read cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}

Implementing "Remember me" Functionality in ASP.NET

What is the best way to implement 'remember me' functionality on an ASP.NET web site?
Should I use custom cookies or is there a simpler method?
Are you using the built in Authenication services provided by ASP.NET? If so, its pretty easy.
For me the solution was differentiating between a browser-session cookie (not to be confused with the asp.net session cookie) and a persistent one - setting a low expiration will create a persistent cookie meaning it gets remembered when the browser is closed and re-opened within the expiration time. The following works for me:
public void SetAuthenticationCookie(LoginView loginModel)
{
if (!loginModel.RememberMe)
{
FormsAuthentication.SetAuthCookie(loginModel.Email, false);
return;
}
const int timeout = 2880; // Timeout is in minutes, 525600 = 365 days; 1 day = 1440.
var ticket = new FormsAuthenticationTicket(loginModel.Email, loginModel.RememberMe, timeout);
//ticket.
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
{
Expires = System.DateTime.Now.AddMinutes(timeout),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
}

How to get SessionID on a request where EnableSessionState="False"

I want to be able to get the SessionID of the currently authenticated session in a WebMethod function where EnableSession = false.
I cannot set EnableSession=true on this request, because another (long running) request on a different page is keeping the SessionState locked (EnableSessionState == "True" not "Readonly").
Is there a consistent way of getting the SessionID from either the ASP.NET Session cookie or the Url for cookieless sessions? I can code it myself but I would rather use a function that is already documented and tested.
Thank you very much,
Florin.
There seems to be no ASP.NET function that can do this, so I made up a hack of my own, which works... for now ;):
private string GetSessionID(HttpContext context)
{
var cookieless = context.Request.Params["HTTP_ASPFILTERSESSIONID"];
if (!string.IsNullOrEmpty(cookieless))
{
int start = cookieless.LastIndexOf("(");
int finish = cookieless.IndexOf(")");
if (start != -1 && finish != -1)
return cookieless.Substring(start + 1, finish - start - 1);
}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
if (cookie != null)
return cookie.Value;
return null;
}
HttpContext.Current.Session.SessionID

Best way to determine if cookies are enabled in ASP.NET?

What is the best method for determining if a users browser has cookies enabled in ASP.NET
Set a cookie, force a redirect to some checking page and check the cookie.
Or set a cookie on every pageload, if it's not already set. For instance, I assume this is to check if cookies are supported to display a message when they try to login that they need to enable cookies. Set your login cookie to some default value for guest users if they don't have the cookie set yet. Then on your login page, check for the user cookie, and if it's not set, then display your message.
#Mattew is right the only way to find out is to set a cookie, redirect, then check it.
Here is a C# function to preform that check you can put this in your page load event:
private bool cookiesAreEnabled()
{
bool cookieEnabled = false;
if(Request.Browser.Cookies)
{
//Your Browser supports cookies
if (Request.QueryString["TestingCookie"] == null)
{
//not testing the cookie so create it
HttpCookie cookie = new HttpCookie("CookieTest","");
Response.Cookies.Add(cookie);
//redirect to same page because the cookie will be written to the client computer,
//only upon sending the response back from the server
Response.Redirect("Default.aspx?TestingCookie=1")
}
else
{
//let's check if Cookies are enabled
if(Request.Cookies["CookieTest"] == null)
{
//Cookies are disabled
}
else
{
//Cookies are enabled
cookieEnabled = true;
}
}
}
else
{
// Your Browser does not support cookies
}
return cookieEnabled;
}
You can do it in javascript also, this way :
function cookiesAreEnabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0;
if (typeof navigator.cookieEnabled == "undefined" && cookieEnabled == 0){
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("test­cookie") != -1) ? 1 : 0;
}
return cookieEnabled == 1;
}
Write a cookie, redirect, see if you can read the cookie.
Well I think if we can save cookie in Global.ASAX session start and read that on page.. isnt that best way?
Essentially the same solution as meda, but in VB.NET:
Private Function IsCookieDisabled() As Boolean
Dim currentUrl As String = Request.RawUrl
If Request.Browser.Cookies Then
'Your Browser supports cookies
If Request.QueryString("cc") Is Nothing Then
'not testing the cookie so create it
Dim c As HttpCookie = New HttpCookie("SupportCookies", "true")
Response.Cookies.Add(c)
If currentUrl.IndexOf("?") > 0 Then
currentUrl = currentUrl + "&cc=true"
Else
currentUrl = currentUrl + "?cc=true"
End If
Response.Redirect(currentUrl)
Else
'let's check if Cookies are enabled
If Request.Cookies("SupportCookies") Is Nothing Then
'Cookies are disabled
Return True
Else
'Cookies are enabled
Return False
End If
End If
Else
Return True
End If
End Function
meda's c# function works though you have to change the line:
HttpCookie cookie = new HttpCookie("","");
to
HttpCookie cookie = new HttpCookie("CookieTest","CookieTest");
You can also check the value of Request.Browser.Cookies. If true, the browser supports cookies.
this is the best way
taken from
http://www.eggheadcafe.com/community/aspnet/7/42769/cookies-enabled-or-not-.aspx
function cc()
{
/* check for a cookie */
if (document.cookie == "")
{
/* if a cookie is not found - alert user -
change cookieexists field value to false */
alert("COOKIES need to be enabled!");
/* If the user has Cookies disabled an alert will let him know
that cookies need to be enabled to log on.*/
document.Form1.cookieexists.value ="false"
} else {
/* this sets the value to true and nothing else will happen,
the user will be able to log on*/
document.Form1.cookieexists.value ="true"
}
}
thanks to Venkat K

Resources