Change a cookie value of a cookie that already exists - c#

I have a cookie called SurveyCookie. Created like so:
var cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
cookie.Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies.Add(cookie);
Which works great. Now the problem comes when I want to change the value "surveyPage" like so.
The below will create a new cookie which is not what I want.
int cookieValue = Convert.ToInt32(Request.Cookies["SurveyCookie"]["surveyPage"]) + 1;
Response.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Then I tried this code below which doesn't work either. The surveyPage is still 1 when it should be 2.
Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Since neither of the above works what does change the cookies value for surveyPage?

From ASP.NET Cookies Overview:
You cannot directly modify a cookie. Instead, changing a cookie
consists of creating a new cookie with new values and then sending the
cookie to the browser to overwrite the old version on the client.
You can try this:
HttpCookie cookie = Request.Cookies["SurveyCookie"];
if (cookie == null)
{
// no cookie found, create it
cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
}
else
{
// update the cookie values
int newSurveyPage = int.Parse(cookie.Values["surveyPage"]) + 1;
cookie.Values["surveyPage"] = newSurveyPage.ToString();
}
// update the expiration timestamp
cookie.Expires = DateTime.UtcNow.AddDays(30);
// overwrite the cookie
Response.Cookies.Add(cookie);

You should always create a new cookie each time you need to modify an existing one , the following works for me :
var cookie = new System.Web.HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = newValue;
cookie.Expires = DateTime.Now.AddDays(1000);
cookie.SameSite = System.Web.SameSiteMode.None;
cookie.Secure = true;
this.HttpContext.Response.Cookies.Add(cookie);

Check out the Response.SetCookie() method as this will set update your existing cookie

Related

ASP.Net delete/expire session cookies

We have a number of internal company ASP.Net applications. All use Forms Authentication and all are session based...
What I am trying to do is when a user logs out of one application he/she is logged out of all applications.
I have some logic that iterates the cookies collection. I can see all the other ASP.Net applications but I can not remove them.
Im currently using the following logic:
// expire all asp.net app tickets
string[] allDomainCookes = HttpContext.Current.Request.Cookies.AllKeys;
foreach (string domainCookie in allDomainCookes)
{
if (domainCookie.Contains("ASPXAUTH"))
{
var expiredCookie = new HttpCookie(domainCookie) { Expires = DateTime.Now.AddDays(-1) };
HttpContext.Current.Response.Cookies.Add(expiredCookie);
}
}
HttpContext.Current.Request.Cookies.Clear();
For some reason they are not being removed. I know they are all there because I have written them to the page. They are just not being removed....is this because these are session cookies?
Also I should add they are all sub-domains of the some domain so ownership should not be an issue?
try this code ..works for me
FormsAuthentication.SignOut();
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(cookie1);
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(cookie2);
Actually...I've just found the problem. I need to specify the domain as well
string[] allDomainCookes = HttpContext.Current.Request.Cookies.AllKeys;
foreach (string domainCookie in allDomainCookes)
{
if (domainCookie.Contains("ASPXAUTH"))
{
var expiredCookie = new HttpCookie(domainCookie) {
Expires = DateTime.Now.AddDays(-1),
Domain = ".mydomain"
};
HttpContext.Current.Response.Cookies.Add(expiredCookie);
}
}
HttpContext.Current.Request.Cookies.Clear();
Cookies only works in the same domain. If it's cross domain, you need another solution. Here is another article about Asp.net cookie

how do i save something in a cookie c# asp.net

All i want to save instance of a class in a cookie just to check something.
Here is my code
class khurram {
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
}
but 'tcook' is not present. what am i doing wrong i don't understand.
i also tried
[serializable]
class khurram {
public string str1{get;set;};
}
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
please help.
thanks in advance
The Value property is defined to be of type string - in both of your examples, you appear to be trying to give it a class khurram
Someething like this may work better for you:
class khurram {
public string str1{get;set;};
}
// later ...
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1.str1;
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.");

C# multi-value cookies not working

Hi I am creating a cookie in the following way:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie.Values["test1"] = "Value1";
cookie.Values["test2"] = "Value2";
cookie.Values["test3"] = "Value3";
//I have also tried cookie.Values.Add("test1", "Value1");
cookie.Expires = DateTime.Now.AddDays(365d);
HttpContext.Current.Response.AppendCookie(cookie); //here I have also tried HttpContext.Current.Response.Cookies.Add(cookie);
but when I read out the cookie using the following code:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie = HttpContext.Current.Response.Cookies["CookieNameHere"];
I always get that the cookie.Values is empty
Is there something I am doing wrong here?
Normally you would write the cookie in a Response, and then read it from subsequent Requests.
I see you're trying to read it from the Response - is this within the context of the same HTTP request, or just a typo?
Try
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieNameHere"];
You have to ask for those Cookies in a Request.
HttpCookie cookie = Request.Cookies["CookieName"];

redirection between asp .net interfaces using cookies without querystring

I have two asp .net interfaces:
1. app1.domain.com
2. app2.domain.com
In default page of both, there is a link button from which we can switch between them. Previously we use query strings to pass username and password. But now we want to use cookies.
So in click event of link button, I have code like this:
HttpCookie cookie = new HttpCookie("MYCookie", Guid.NewGuid().ToString());
cookie.Domain = "domain.com";
cookie.Expires = DateTime.UtcNow.AddHours(1);
cookie.HttpOnly = false;
cookie.Secure = true;
cookie.Values.Add("Username", Username.ToString());
cookie.Values.Add("UserId", UserId.ToString());
Response.Cookies.Add(cookie);
Response.Redirect(destinationAddress);
Now, in default page of other application am reading cookie as:
protected override void InitializeCulture() {
if (Request.Cookies["MYCookie"] != null) {
HttpCookie cookie = null;
cookie = Request.Cookies.Get("MYCookie");
}
}
but here am finding Request.Cookies["MYCookie"] as null. Am i missing anything? Please advice.
It looks to me like the problem is your domain.
Change cookie.Domain = "domain"; to be cookie.Domain = ".domain.com";
I think you need to add HttpCookie same Path property for both app1 and app2
Response.Redirect generates ThreadAbortException.
All the changes made in your cookie will be lost. so you can use,
<meta http-equiv="Refresh" content="10; URL=your url" />
c# code:
System.Web.UI.HtmlControls.HtmlMeta meta = new System.Web.UI.HtmlControls.HtmlMeta();
meta.HttpEquiv = "Refresh";
meta.Content = "10; URL=your url";
Page.Header.Controls.Add(meta);
And set you cookie as like
cookie.Domain = ".domain.com";

Delete cookie on clicking sign out

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();

Categories

Resources