I used multidimensional cookie to store a cookie in my application.
For example
HttpCookie MyCookie = Request.Cookies["Temp"] as HttpCookie;
if (MyCookie != null)
{
MyCookie.Values["SID"] = Session.SessionID;
MyCookie.Values["NAME"] = "NAME";
MyCookie.Values["abc"] = "abc";
MyCookie.Values["xyz"] = "xyz";
...
}
Now to retrieve this multidimensional cookie I used.
string s = Request.Cookies["Temp"]["SID"]
My question is I want to expire only "SID" value from the "Temp" cookie. I tried with this
Request.Cookies["Temp"]["SID"] = null;
but it's not working. What should I do clear particular index from multidimensional cookie?
This is already answered in the following question: ASP.NET Cookie Sub-Value Deletion
HttpCookie.Values is a NameValueCollection, so you can modify that collection - but you will need to re-send the cookie as a new one to overwrite the old one:
HttpCookie cookie = Request.Cookies["Temp"];
if(cookie != null)
{
cookie.Values.Remove("SID");
Response.AppendCookie(cookie);
}
This is also explained in the following MSDN page: http://msdn.microsoft.com/en-us/library/aa289495(v=vs.71).aspx#vbtchaspnetcookies101anchor9
This will do.
Request.Cookies["Temp"].Values["SID"] = null;
Hope it helps. :)
Related
I create some cookies in logon.aspx.cscodebehind thatc read and contain user info from DB with data reader .
HttpCookie UID = new HttpCookie("ID");
Response.Cookies["UID"].Value = Recordset[0].ToString();
Response.Cookies.Add(UID);
HttpCookie UName = new HttpCookie("Username");
Response.Cookies["Username"].Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
HttpCookie Pass = new HttpCookie("Pass");
Response.Cookies["Pass"].Value = Recordset[4].ToString();
Response.Cookies.Add(Pass);
HttpCookie Admins = new HttpCookie("Admin");
Response.Cookies["Admin"].Value = Recordset[12].ToString();
Response.Cookies.Add(Admins);
HttpCookie Mails = new HttpCookie("Emails");
Response.Cookies["Emails"].Value = Recordset[9].ToString();
Response.Cookies.Add(Mails);
Response.Redirect("../default.aspx");
when i trace the code every thing is good and data hold by cookies.
Now when i read these cookies in master page or other content page, i can't.
in other worlds the cookies not recognize by their names(or keys)
if (Request.Cookies["Username"] !=null)
{
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
pnlUsersNavigation.Visible = true;
LoginMenu.Visible = false;
RegisterMenu.Visible = false;
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
//lblWelcomeUser.Text = Request.Cookies["Username"].Value.ToString();
if (Request.Cookies["Admin"].Value.ToString()=="True")
{
lblWelcomeUser.Text = "WELCOME ADMIN";
// Show Menu that is only for Admin
}
where is the problem in this code?
It appears that you might be overwriting the cookie with a good value, with a new empty cookie.
// new cookie created - empty
HttpCookie UName = new HttpCookie("Username");
// new cookie created with a value
Response.Cookies["Username"].Value = Recordset[3].ToString();
// overwrite new cookie with value with new empty cookie
Response.Cookies.Add(UName);
Create the cookie, set the value, then add the cookie to the response.
HttpCookie UName = new HttpCookie("Username");
UName.Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
Also note that as Paul Grimshaw pointed out, you can add multiple values to the same cookie.
Download Fiddler to check request/response to ensure your cookies contain the correct values and such... http://fiddler2.com/get-fiddler
Also be careful about Man-in-the-middle attacks. Storing usernames and passwords in plain text is not such a good idea to begin with.
This doesn't look like a very secure way of securing access to your application. Try looking at ASP.NET membership.
Otherwise try setting an expiry date. Also, as this example shows, you may want to store all the above info in one cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UID"] = Recordset[0].ToString();
myCookie["Username"] = Recordset[3].ToString();
//...etc...
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
Also, from MSDN:
By default, cookies are shared by all pages that are in the same
domain, but you can limit cookies to specific subfolders in a Web site
by setting their Path property. To allow a cookie to be retrieved by
all pages in all folders of your application, set it from a page that
is in the root folder of your application and do not set the Path
property. If you do not specify an expiration limit for the cookie,
the cookie is not persisted to the client computer and it expires when
the user session expires. Cookies can store values only of type
String. You must convert any non-string values to strings before you
can store them in a cookie. For many data types, calling the ToString
method is sufficient. For more information, see the ToString method
for the data type you wish to persist.
I've been searching a solution for this problem but i couldn't have one. By the way i can't understand the reason of my problem.
The problem is:
My web application has a login page and gets logged user id from cookie. It worked before but 5-6 days ago because of something changed it didn't worked with IE. Now it doesn't work with any browser.
I can see the cookie in Chrome. When looked with Internet Explorer Developer Tool sometimes the cookie written but still can't read by IE
My web app is on Windows Server 2008 R2 BTW
Set my web.config:
<httpCookies domain=".domainname.com" httpOnlyCookies="false" requireSSL="false" />
Here is my SetCookie code
<!-- language: c# -->
string uId = "userID";
DateTime expireDate = DateTime.Now.AddDays(3);
HttpContext.Current.Response.Cookies["cookieName"]["uID"] = uId;
HttpCookie aCookie = new HttpCookie("cookieName");
aCookie.Values["uID"] = uId;
aCookie.Path = "/";
aCookie.Expires = expireDate;
aCookie.HttpOnly = false;
aCookie.Domain = "domainname.com";
aCookie.Name = "cookieName";
HttpContext.Current.Response.Cookies.Add(aCookie);
And this GetCookie code
<!-- language: c# -->
if (HttpContext.Current.Request.Cookies["cookieName"] != null)
{
System.Collections.Specialized.NameValueCollection UserInfoCookieCollection;
UserInfoCookieCollection = HttpContext.Current.Request.Cookies["cookieName"].Values;
userID = HttpContext.Current.Server.HtmlEncode(UserInfoCookieCollection["uID"]);
}
The scenario is:
trying to log in
SetCookie method triggered
End of SetCookie method there are two cookies "cookieName" and
"ASP.NET SessionId"
GetCookie method triggered
There is only "ASP.NET SessionId" and session value still same
Thanks for any help.
My problem solved. Changed my code to this
string uId = "userID";
DateTime expireDate = DateTime.Now.AddDays(3);
var httpCookie = HttpContext.Current.Response.Cookies["cookieName"];
if (httpCookie != null)
{
httpCookie["uID"] = uId;
HttpContext.Current.Response.Cookies.Add(httpCookie);
}
else
{
HttpCookie aCookie = new HttpCookie("cookieName");
aCookie.Values["uID"] = uId;
aCookie.Expires = expireDate;
HttpContext.Current.Response.Cookies.Add(aCookie);
}
This one had me stumped. But managed to solve it as follows. So basically setting the expiry as part of the initialiser does not work. Setting it after adding the cookie to the response object works!
I have some asp.net pages that read and write cookie values. During the life cycle of a page it may update the cookie value and then need to read it again further in the code. What I've found is that it's not getting the latest value of the cookie until a page refresh. Is there a way around this? Here's the code I'm using to set and get the values.
public static string GetValue(SessionKey sessionKey)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiePrefix];
if (cookie == null)
return string.Empty;
return cookie[sessionKey.SessionKeyName] ?? string.Empty;
}
public static void SetValue(SessionKey sessionKey, string sessionValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiePrefix];
if (cookie == null)
cookie = new HttpCookie(cookiePrefix);
cookie.Values[sessionKey.SessionKeyName] = sessionValue;
cookie.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Set(cookie);
}
What you're missing is that when you update the cookie with SetValue you're writing to the Response.Cookies collection.
When you call GetValue you're reading from the Request.Cookies collection.
You need to store the transient information in a way that you access the current information, not just directly the request cookie.
One potential way to do this would be to writer a wrapper class that with rough psuedo code would be similar to
public CookieContainer(HttpContext context)
{
_bobValue = context.Request.Cookies["bob"];
}
public Value
{
get { return _bobValue; }
set {
_bobValue = value;
_context.Response.Cookies.Add(new Cookie("bob", value) { Expires = ? });
}
}
I ran into needing to do similar code just this week. The cookie handling model is very strange.
Start using Sessions to store your information, even if it's only temporary.
Cookies rely on a header being sent to the browser before the page has rendered. If you've already sent information to the client then proceed to set a cookie, you're going to see this "page refresh delay" you've described.
If it's necessary to have this value, use a session variable between the time you set the cookie and when you refresh the page. But, even then I would just recommend avoiding settings cookies so late in the processing step and try to set it as early as possible.
I have a cookie called "g" with values "y" or "n"
I set it like this:
Response.Cookies("g").Value = "y"
Response.Cookies("g").Expires = DateTime.Now.AddHours(1)
I change it like this:
Request.Cookies("g").Value = "n"
and I try to destroy it like this
Response.Cookies("g").Expires = DateTime.Now.AddHours(-1)
The cookie gets set fine, but I cannot change its value or destroy it
Thanks!
Try deleting it this way:
if (Request.Cookies["g"] != null)
{
HttpCookie myCookie = new HttpCookie("g");
myCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie);
}
I think if you try creating the cookie and adding it to the Response like this it should work.
You want to add in a new cookie to the response that has the same name. Also I recommend going back a day and not just an hour.
To change the value of the cookie do this:
if (Request.Cookies["g"] != null)
{
HttpCookie myCookie = new HttpCookie("g");
myCookie.Expires = DateTime.Now.AddHours(1);
myCookie.Value = "n";
Response.Cookies.Add(myCookie);
}
The important thing to note with these examples is that we are observing the read-only request collection to see what is already in there, and then we are making changes or deleting by adding a new cookie to replace the one that was there before.
You cannot change the Request cookie, you can only "re-set" it in your response. Hence, you need to set the same cookie in your Response.
However the Expire-trick should work, but sometimes the DST (daylight saving time) might confuse the browser. Have you tried using a very old DateTime (like, 1970) in order to expire the cookie?
I have a ASP MVC App with some seemingly simple code to save and retrieve cookies but for some reason they won't persist. The code in the controller is :
if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
{
HttpCookie cookie = new HttpCookie("CountryPreference");
cookie.Value = country;
cookie.Expires = DateTime.Now.AddYears(1);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
And to load it again :
if (System.Web.HttpContext.Current.Request.Cookies["CountryPreference"] != null)
{
System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Expires = DateTime.Now.AddYears(1);
data.Country = System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Value;
}
For some reason the cookie is always null?
The problem lies in following code:
if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
When you try to check existence of a cookie using Response object rather than Request, ASP.net automatically creates a cookie.
Check this detailed post here: http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx
Quote from the article in case the link goes down again ....
The short explanation, if you don’t
like to read the entire story
If you use code like “if
(Response.Cookies[“mycookie”] != null)
{ … }”, ASP.Net automatically
generates a new cookie with the name
“mycookie” in the background and
overwrites your old cookie! Always use
the Request.Cookies-Collection to read
cookies!
[ More detail in the article ]
In resume, don't use "Response" to read cookies, use "Request".