Change value of an existing Cookie [duplicate] - c#

This question already has answers here:
Change a cookie value of a cookie that already exists
(3 answers)
Closed 5 years ago.
I'm trying to modify the value of my cookie but It doesn't modify instead it appends. What am I doing wrong?
Currently, SkillId cookie contains 112 in value, I want to update its value with whatever is in my variable qualifyBySkill.
string qualifyBySkill = "189";
HttpCookie cookie = Request.Cookies["SkillId"];
if (cookie != null)
{
cookie.Values["SkillId"] = qualifyBySkill;
}
cookie.Expires = DateTime.UtcNow.AddDays(1);
Response.Cookies.Add(cookie);
What happens is, after this code it sets 112&SkillId=189 instead of 189 in Value. What am i doing wrong?

When thinking about cookies, it's helpful to remember that cookies are created by and stored by the browser alone. They are not passed back and forth between the browser and the server.
Request.Cookies contains a list of cookie headers that the browser sent, informing the server of the existence of a subset of cookies; they are not the actual cookies, and in fact lack much of the information contained in normal cookie record (e.g. domain and path).
Response.Cookies contains only set-cookie headers, asking the browser to create a cookie. This list is usually empty.
To change a cookie on the browser, the server must set a new cookie header. The important word being new.
string qualifyBySkill = "189";
var cookie = new HttpCookie("SkillId", qualifyBySkill);
cookie.Expires = DateTime.UtcNow.AddDays(1);
Response.Cookies.Add(cookie);

Related

C# Cookie not being set on browser [duplicate]

This question already has answers here:
Cross-Domain Cookies
(17 answers)
Closed 7 years ago.
I am trying to set a cookie for domain b.com, but the page which is setting the cookie is on a.com
the code is as below
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
myCookie.domain = "b.com";
myCookie.path ="/";
Response.Cookies.Add(myCookie);
I'm pretty sure this part of the code is working as I am able to do a request.cookies to get the values. However, it is not really set on my browser. When I open a browser (such as Chrome and Firefox) and view all the cookies, then search for domain "b.com", nothing is found! Is the cookie is not really set? I tried all night to figure this out but I can't. What am I doing wrong?
As stated in this question, there is no way to create a cookie for a different domain. If it's possible for you, you could work your way with redirections from domain to domain to set the cookies.

How do I manually delete a cookie in asp.net MVC 4

I need to delete authentication cookie manually (Instead of using FormsAuthentication.SignOut whcih for some reasons does not work). I tried
System.Web.HttpContext.Request.Cookies.Remove(cookieName); // for example .ASPXAUTH
System.Web.HttpContext.Response.Cookies.Remove(cookieName); // for example .ASPXAUTH
FormsAuthentication.SignOut(); // I don't know why this one does not work
Neither of those command work. In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.
Try:
if (Request.Cookies["MyCookie"] != null)
{
var c = new HttpCookie("MyCookie")
{
Expires = DateTime.Now.AddDays(-1)
};
Response.Cookies.Add(c);
}
More information on MSDN.
c.Expires = DateTime.Now.AddDays(-1);
This does not clear cookies instantly.
Use this: c.Expires = DateTime.Now.AddSeconds(1);
This will clear cookies instantly.

Updating the value of a cookie not working

I need to get the value of a cookie and update it. I must be doing something wrong because my cookie does not get updated. This is my code:
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(EconnectConstants.FILE_SHARE_DOCUMENTS))
{
var existingCookie = HttpContext.Current.Request.Cookies[EconnectConstants.FILE_SHARE_DOCUMENTS];
existingCookie.Value = encriptedInput;
existingCookie.Expires = DateTime.Now.AddMonths(1);
HttpContext.Current.Response.Cookies.Set(existingCookie);
}
else
{
var cookie = new HttpCookie(EconnectConstants.FILE_SHARE_DOCUMENTS, encriptedInput);
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.Value = encriptedInput;
HttpContext.Current.Response.Cookies.Add(cookie);
}
Can anyone please tell me what I am doing wrong?
This question is very old, but I faced this issue a time ago. As #argaz explain, since you are updating a value in the Response, you cannot get it from another object (the Request). Values are transferred from Request to Response in the next postback.
So, if your cookie stores data only valid for the current session AND
you cannot wait to a postback happens, then instead implement a fake (as reading cookie values from same just updated Response according to special condition or force a postback to same page), consider the use Session object, which is not dependent of postbacks.
This seems suspicious:
HttpContext.Current.Request.Cookies.Set(existingCookie);
You are changing a property of the request object, it should not affect the response (which affects what is stored at the user).
You can probably remove the if and do:
HttpContext.Current.Request.Cookies[EconnectConstants.FILE_SHARE_DOCUMENTS].Value = encriptedInput;
HttpContext.Current.Request.Cookies[EconnectConstants.FILE_SHARE_DOCUMENTS].Expires = DateTime.Now.AddMonths(1);

Difference between HttpResponse: SetCookie, AppendCookie, Cookies.Add

there are some different ways to create multi value cookies in ASP.NET:
var cookie = new HttpCookie("MyCookie");
cookie["Information 1"] = "value 1";
cookie["Information 2"] = "value 2";
// first way
Response.Cookies.Add(cookie);
// second way
Response.AppendCookie(cookie);
// third way
Response.SetCookie(cookie);
When should I use which way? I've read that SetCookie method updates the cookie, if it already exits. Doesn't the other ways update the existing cookie as well?
And is the following code best practice for writing single value cookies?
Response.Cookies["MyCookie"].Value = "value";
If I remember correctly both
Response.Cookies.Add(..)
and
Response.AppendCookie(..)
will allow multiple cookies of the same name to be appended to the response.
On the other hand
Response.SetCookie(..)
and
Response.Cookies[key].Value = value;
will always overwrite previous cookies of the same name.
When should I use which way?
It's depends on what Cookie operation you want to do.
Note that Add and AppendCookie are doing the same functionality except the fact that with AppendCookie you're not referencing the Cookies property of the Response class and it's doing it for you.
Response.Cookies.Add - Adds the specified cookie to the cookie
collection.
Response.AppendCookie - Adds an HTTP cookie to the
intrinsic cookie collection
Response.SetCookie - Updates an existing cookie in the cookie
collection.
Exceptions will not be thrown when duplicates cookies are added or when attempting to update not-exist cookie.
The main exception of these methods is: HttpException (A cookie is appended after the HTTP headers have been sent.)
The Add method allows duplicate cookies in the cookie collection. Use the Set method to ensure the uniqueness of cookies in the cookie collection.
Thanks for MSDN!
To piggyback on tne's comment in Wiktor's reply, AppendCookie and SetCookie shouldn't be used - they're for internal use by the .NET framework. They shouldn't be public but they are, my guess would be as a hack for the IIS pipeline somewhere else.
So you should do your cookie setting this way (or write an extension method for setting multiple cookies):
string cookieName = "SomeCookie";
string cookieValue = "2017";
if (Response.Cookies[cookieName] == null)
{
Response.Cookies.Add(new HttpCookie(cookieName, cookieValue));
}
else
{
Response.Cookies[cookieName].Value = cookieValue;
}

Cookies don't persist after refresh

I am using c# and mvc. I am trying to write a cookie to the user browser. But after a refresh of the browser the cookie disappears.
This is my code for writing the cookie:
movieCookie = new HttpCookie(cookieName);
movieCookie.Value = "test;
movieCookie.Expires = DateTime.Now.AddDays(30);
//add the cookie
HttpContext.Current.Response.Cookies.Add(movieCookie);
and the one for reading the cookie:
//check if such cookie exist
HttpCookie movieCookie = null;
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
movieCookie = HttpContext.Current.Request.Cookies[cookieName];
Another thing to add is that when I searched "AllKeys" like so:
HttpContext.Current.Request.Cookies.AllKeys
it shows an empty string array, for some reason.
any ideas?
Some possibly silly questions
Check your web-servers time and date, are they set correctly, if they are (in your case) 2 years out it will expire cookies immediately.
Check that cookieName is the same
Check that after setting the cookie to the response your not redirecting before the cookie is set. For a cookie to be set you need to set headers and push them out.
I solved it. It appears that in MVC the "return view" after the cookie creation, cause the cookie not to be saved.

Categories