Cookies become null when page is loaded - c#

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.

Related

New cookie value not persisting

Having an issue when trying to change a cookie value. My app checks if the user is browsing with an old browser like IE8. If so, he's redirected to a specific page to inform about compatibility issues. This page contains a link with a query string to the main page.
The idea is to use a cookie with the value set to true after the first redirect (by checking if that specific query string exists), to prevent further redirections.
Current code:
HttpCookie _forceEntry = Request.Cookies["_forceEntry"];
if (_forceEntry == null)
{
_forceEntry = new HttpCookie("_forceEntry");
_forceEntry.Values.Add("_forceEntry", "false");
Response.Cookies.Add(_forceEntry);
}
if (Request.QueryString["ForceOldIE"] != null)
{
_forceEntry["_forceEntry"] = "true";
}
if (_unsupportedBrowser.Values["_unsupportedBrowser"].ToString() == "true" && _forceEntry["_forceEntry"] == "false")
Response.Redirect("~/SupportedBrowsers/Index?applicationId=1");
This works whenever the query string exists. The cookie value is changed to true. But when I try to navigate to another page, the value is returning false again, getting me redirected again.
How come this is happening? Shouldn't the cookie value persist as true across other pages after being set on the last if?

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";

HTTP Module and Cookies in Sharepoint 2007

I have some proof concept code for a HTTP module. The code checks to see if a cookie exists, if so it retrieves a value, if the cookie does not exist it creates it and sets the value.
Once this is done I write to the screen to see what action has been taken (all nice and simple). So on the first request the cookie is created; subsequent requests retrieve the value from the cookie.
When I test this in a normal asp.net web site everything works correctly – yay! However as soon as I transfer it to SharePoint something weird happens, the cookie is never saved - that is the code always branches into creating the cookie and never takes the branch to retrieve the value - regardless of page refreshes or secondary requests.
Heres the code...
public class SwithcMasterPage : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
// register handler
context.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
void PreRequestHandlerExecute(object sender, EventArgs e)
{
string outputText = string.Empty;
HttpCookie cookie = null;
string cookieName = "MPSetting";
cookie = HttpContext.Current.Request.Cookies[cookieName];
if (cookie == null)
{
// cookie doesn't exist, create
HttpCookie ck = new HttpCookie(cookieName);
ck.Value = GetCorrectMasterPage();
ck.Expires = DateTime.Now.AddMinutes(5);
HttpContext.Current.Response.Cookies.Add(ck);
outputText = "storing master page setting in cookie.";
}
else
{
// get the master page from cookie
outputText = "retrieving master page setting from cookie.";
}
HttpContext.Current.Response.Write(outputText + "<br/>");
}
private string GetCorrectMasterPage()
{
// logic goes here to get the correct master page
return "/_catalogs/masterpage/BlackBand.master";
}
This turned out to be the authentication of the web app. To work correctly you must use a FQDM that has been configured for Forms Authentication.
You can use Fiddler or FireBug (on FireFox) to inspect response to see if your cookie is being sent. If not then perhaps you can try your logic in PostRequestHandlerExecute. This is assuming that Sharepoint or some other piece of code is tinkering with response cookies. This way, you can be the last one adding the cookie.

When to use Request.Cookies over Response.Cookies?

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;
}

Categories

Resources