C# httpcookie is not being saved .net 3.5 - c#

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.

Related

Cookies become null when page is loaded

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.

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

Cannot find the cookies in asp.net c#

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...

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