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?
Related
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.
The cookie used for session in ASP.NET MVC is httpOnly (property set to true).
Is there a way to make it not httpOnly?
I want to be able to access this cookie from javascript.
Even if it is less secure than the "What if all the universe stands against me?!" default setting.
If you REALLY need it you could try to add this to your Global.asax:
void Application_EndRequest(Object sender, EventArgs e)
{
if (Response.Cookies.Count > 0)
{
foreach (string s in Response.Cookies.AllKeys)
{
if (s == "ASP.NET_SessionId")
{
Response.Cookies["ASP.NET_SessionId"].HttpOnly = false;
}
}
}
}
Solution was taken from here.
I built a system that uses cookies to store search params across the site.
On the home page there are links and I wanted to use jQuery to save a cookie with the item id in it.
But on click the user is then sent to an advanced search page where they can use .net controls to modify the search. The cookies are saved again but they needed to be writable by the js on the home page when the user browsed back.
So I set HttpOnly like this:
var cookie = new HttpCookie(name)
{
Value = val,
HttpOnly = false // #DEV search cookies can be modified by JS
};
HttpContext.Current.Response.Cookies.Add(cookie);
I have an application that leverages a cookie to support a quasi-wizard (i.e. it's a set of pages that are navigated to by each other, and they must occur in a specific order, for registration).
When the Logon.aspx page is loaded - the default page - the browsers cookies look right.
There's one cookie and it has the right value. This ensures that the next page, which is an enrollment agreement, knows that it was loaded from the Logon.aspx page. However, when I get to that page the browsers cookies look much different:
Now we have two of the same cookie.
This doesn't appear to be causing any real issues - but I can't be sure it won't. So, let me show you the code I'm using to set the cookie (because maybe there's something wrong with it):
if (!this.IsPostBack)
{
Utility.HandleReferrer(Request, Response, "Logon.aspx");
Response.Cookies["lastpage"].Value = "Enroll.aspx";
}
and the HandleReferrer method looks like this:
static public void HandleReferrer(HttpRequest request, HttpResponse response, string expectedReferrer)
{
var cookie = request.Cookies["lastpage"];
if (cookie != null && cookie.Value.ToLower().Contains(expectedReferrer.ToLower()))
{
return;
}
response.Redirect("Logon.aspx");
}
So, why in the world does it duplicate this cookie? It doesn't ever seem to create more than two.
I suggest you do one of the following.
First, get the latest glimpse and try again.
If it is still showing 2 cookies with that name then get firebug and/or fiddler and look at it that way. If I had to take a guess I'd say there's either something wrong in glimpse or something wrong in how you are interpreting the results. Perhaps glimpse is showing what cookies existed before and then after the request was processed?
A third option is to simply emit the cookies collection from your own .net code. Something like:
foreach(HttpCookie cookie in request.Cookies) {
Response.Write(String.Format("{0} = {1}", cookie.Name, cookie.Value));
}
and see what happens.
I tried another approach, by creating a method that will return the latest cookie occurrence, this way I'll always get the right data.
This method expect the collection of cookies from Request, and the name of the searched cookie, and returns the latest ticket (the information that is normally encrypted)
private static FormsAuthenticationTicket GetLatestCookie(HttpCookieCollection cookies, string cookieName) {
var cookieOccurrences = new List<FormsAuthenticationTicket>();
for (int index = 0; index < cookies.Count; index++) {
if (cookies.GetKey(index) == cookieName) {
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookies[index].Value);
cookieOccurrences.Add(ticket);
}
}
DateTime oldestTime = DateTime.MinValue;
FormsAuthenticationTicket oldestTicket = null;
foreach (var formsAuthenticationTicket in cookieOccurrences) {
if (formsAuthenticationTicket.Expiration > oldestTime) {
oldestTime = formsAuthenticationTicket.Expiration;
oldestTicket = formsAuthenticationTicket;
}
}
return oldestTicket;
}
I am setting cookie value in a usercontrol[A] and reading the value in the another usercontrol [B].
But the value is only available on page refresh in the server side. I can see the updated value in firebug cookie tab.
If i refersh the page the correct value is diplaying inthe page.
How to fix this issue?Below is the code i am using to read the cookie in usercontrol[B].
Its always the old value not the new value that i set in the usercontrol[A]
HttpCookie cookieTool = Request.Cookies["previousTool"];
string strSessionReturnToolTitle = "";
string strSessionReturnToolURL = "";
if (cookieTool != null)
{
// Response.Write("<BR>Cookie value " + cookieTool["returnToolurl"].ToString());
if (Request.UrlReferrer == null)
{
cookieTool.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookieTool);
}
else
{
strSessionReturnToolTitle = cookieTool["returnTooltitle"];
strSessionReturnToolURL = Server.UrlDecode(cookieTool["returnToolurl"]);
}
}
Request.Cookies is incoming. Response.Cookies is outgoing.
Request.Cookies only knows about the current request. I don't think it updates until the following request when you add via Response.Cookies.
You could try getting the cookie via Response.Cookies["previousTool"] in case Request.Cookies["previousTool"] is null.
If that doesn't work you'll need another way, such as storing the value in the Session or HttpContext.Current.Items.
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;
}