I am creating a web page with .net 2.0 and I want to check if it is the first time visit for the user.
I am using the code block in pageload():
String CookieName = "Cookie";
String CookieValue = "TEST";
if (Request.Cookies[CookieName] != null)
{
Label3.Visible = true;
if (Request.Cookies[CookieName].Value == CookieValue)
{
Label3.Text = "Cookie already exists: " + Request.Cookies[CookieName].Value.ToString();
}
else
Label3.Text = "Cookie var içerisinde: " + Request.Cookies[CookieName].Value.ToString();
}
else
{
Label3.Visible = true;
HttpCookie MyCookie=new HttpCookie(CookieName,CookieValue);
Response.Cookies.Add(MyCookie);
Label3.Text = "Cookie created. " + Request.Cookies[CookieName].Value.ToString();
}
Everything seems to be working, as I run the code "Label3" becomes "Cookie created. Cookie". And after another postback "Label3" becomes "Cookie already exists. Cookie" as it should be.
But I couldn't find my cookies anywhere in my local harddrive.(even if I didn't end the session)
And after ending session and re-run the code, it starts again with "Cookie created. Cookie" which means it couldn't find the previous cookie.
It is obvious that something is missing. I tried to add expry date and path to the cookie. None of them worked for me.
Thank you in advance.
Cagri
But I couldn't find my cookies anywhere in my local harddrive.(even if I didn't end the session)
If you have Chrome, and why don't you :), use it's built-in Dev tools CtrlShiftI and select the Resources tab and boom! not just cookies!:
If you look above, in the Expires column, you'll see one cookie expires at the end of the browser Session, while the other has a set Date.
The cookies you are creating above are Session (dies after browser close).
If you want to them to be persistent and survive a browser close, define Expires property like so:
Response.Cookies.Add(new HttpCookie(CookieName, "hello persistent") { Expires = DateTime.Now.AddDays(1) });
Hth...
Related
I am creating a model,serializing & assigning into cookie and passing it to next Page.
I am able to get cookie values in next page in all browser except
MAC -Yoshemite - Safari
IOS - IPHONE 6 Mobile- Safari
Do I need to update the below code to work in Safari.
string CookieName= "dsResponse";
string json = new JavaScriptSerializer().Serialize(model);
if (HttpContext.Current.Request.Cookies[CookieName] != null)
{
HttpContext.Current.Response.Cookies[CookieName].Expires = DateTime.Now.AddDays(-1);
}
HttpContext.Current.Response.SetCookie(new HttpCookie(CookieName)
{
Value = json,
HttpOnly = false,
Expires = DateTime.Now.AddSeconds(Convert.ToInt32(ConfigurationManager.AppSettings["cookiesecond"]))
});
1st: you are overwriting the cookie - not expiring it with this code.
The response object is sent once - with your "new" cookie.
If the cookie exists - just change its value and/or the content.
I would check your assumption on AppSettings["cookiesecond"]
Also try this:
If Request.ServerVariables("http_user_agent").IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) <> -1 Then
Me.Page.ClientTarget = "uplevel"
It may be the browser caps not matching...
There was some comma was coming in JSON data and its breaking at the time of deserilze the data.
var cookieValue = (json).Replace(";", "").Replace(",", "***");
if (HttpContext.Current.Request.Browser.Type.ToLower().Contains("safari"))
{
HttpContext.Current.Response.AddHeader("Set-Cookie", sessionName + "=" + cookieValue + "; path=/;");
}
By default cookie not allowed for iOS safari browser. We have to enable cookies setting from iOS safari browser,
Solution :-
-we have implemented local storage(java script concept)to overcome the cookie problems in iOS safari browser.
I am having a lot of trouble trying to figure out why cookies I am creating in C# net 3.5 are not being saved.
On one page I have this code:
HttpCookie myCookie = new HttpCookie("LastPage");
myCookie.Domain = ".domain.com";
myCookie.Value = Request.Url.AbsoluteUri;
myCookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(myCookie);
On a different page I have this code to put all the cookies in a UL
foreach (String thisKey in Request.Cookies.AllKeys)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HttpCookie thisCookie = Request.Cookies[thisKey];
li.InnerHtml = thisCookie.Name + " = " + thisCookie.Value;
ulCookies.Controls.Add(li);
}
So why is it when I run the first page then run the second page in a different tab in the same browser, the cookie "LastPage" does not appear in the UL? I'm also unable to access the "LastPage" cookie on other pages.
I did notice that each time I reload the second page the ASP.NET_SessionId cookie is set to a different value. I think that is relevant to the issue, but I'm not sure.
Thanks in advance.
I have two asp.net pages. I set cookies using following code in Login Page.
HttpCookie cookie = new HttpCookie("sample");
cookie.Values.Add(cookieValues);
cookie.Expires = DateTime.Now.AddMinutes(60);
HttpContext.Current.Response.Cookies.Add(cookie);
Cookie is set successfully with expired date. I can see it on Watch window of Visual Studio.
However, when I tried to look for the values in another page during page load, both request and response cookies are null.
HttpCookie respCookie = HttpContext.Current.Request.Cookies["sample"];
if (respCookie != null)
{
DateTime expDate = respCookie.Expires;
if (expDate > DateTime.Now)
return respCookie;
else
return null;
}
else
return null;
Try disabling browser extensions or running your page in anonymous mode.
I was using Avast browser extension which messed with my cookies, worked for me.
I am creating the cookie using the code below, How to read the txtusername value in another page and how to delete the cookie when I click sign out(code for sign out). I am new to programming please help.
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
You should never store password as a cookie. That's a very big security threat. To delete a cookie, you really just need to modify and expire it. You can't really delete it, i.e. remove it from the user's disk. Check out this documentation.
Here is a sample:
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
Response.Cookies.Add(aCookie); // overwrite it
}
You cannot directly delete a cookie, you have to set it to expire before the current date:
if (Request.Cookies["clienDetails"] != null)
{
HttpCookie myCookie = new HttpCookie("clienDetails");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
You can read more about it here.
Furthermore I really encourage you to not write your own security but to read up on asp.net membership. More secure and easier to use. As I can see many flaws in your security model. Storing the password in plain text in a cookie is really really bad.
EDIT:
As you now changed your code, you have to do this to remove the cookie:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
FYI this did not work for me using Chrome 69 with the Continue where you left off feature enabled. Similar issue with Firefox. Disabling this feature worked for me.
See
Chrome doesn't delete session cookies
How to delete or expire a cookie in Chrome using Asp.Net
In my case this code worked:
Response.Cookies.Delete("access_token");
return Ok();
Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processing? Or is there more to it?
They are 2 different things, one SAVES [Response], the other READS [Request]
in a Cookie (informatics speaking) :)
you save a small file for a period of time that contains an object of the type string
in the .NET framework you save a cookie doing:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
You wrote a cookie that will be available for one minute... normally we do now.AddMonth(1) so you can save a cookie for one entire month.
To retrieve a cookie, you use the Request (you are Requesting), like:
HttpCookie myCookie = Request.Cookies["MyTestCookie"];
// Read the cookie information and display it.
if (myCookie != null)
Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
Response.Write("not found");
Remember:
To Delete a Cookie, there is no direct code, the trick is to Save the same Cookie Name with an Expiration date that already passed, for example, now.AddMinutes(-1)
this will delete the cookie.
As you can see, every time that the time of life of the cookie expires, that file is deleted from the system automatically.
In a web application the request is what comes from the browser and the response is what the server sends back. When validating cookies or cookie data from the browser you should use the Request.Cookies. When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.
When writing a cookie, use Response but reading may depend on your situation. Normally, you read from Request but if your application is attempting to get a cookie that has just been written or updated and the round trip to the browser has not occured, you may need to read it form Response.
I have been using this pattern for a while and it works well for me.
public void WriteCookie(string name, string value)
{
var cookie = new HttpCookie(name, value);
HttpContext.Current.Response.Cookies.Set(cookie);
}
public string ReadCookie(string name)
{
if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
{
var cookie = HttpContext.Current.Response.Cookies[name];
return cookie.Value;
}
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
{
var cookie = HttpContext.Current.Request.Cookies[name];
return cookie.Value;
}
return null;
}
The cookies comes from the browser in the Request.Cookies collection. That is where you read the cookies that was sent.
To send cookies back to the browser you put them in the Response.Cookies collection.
If you want to delete a cookie, you have to tell the browser to remove it by sending the cookie with an expiration date that has passed. The browser is using the local time of the client computer so if you are using the server time to create a date, be sure to subtract at least one day to be sure that it has actually passed in the clients local time.
When i create or update a cookie in .NET i normally do it to both the request and response cookie collection. That way you can be sure if you try to read the cookie further down the page request sequence it will have the correct information.
Andrew's Code gave an error in "AllKeys.Contains" Method. So I corrected a little..
public void WriteCookie(string strCookieName, string strCookieValue)
{
var hcCookie = new HttpCookie(strCookieName, strCookieValue);
HttpContext.Current.Response.Cookies.Set(hcCookie);
}
public string ReadCookie(string strCookieName)
{
foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
{
if (strCookie == strCookieName)
{
return HttpContext.Current.Response.Cookies[strCookie].Value;
}
}
foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
{
if (strCookie == strCookieName)
{
return HttpContext.Current.Request.Cookies[strCookie].Value;
}
}
return null;
}