Am storing and retreiving the cookie using the coding
public static void SetCookie(string key, string value, int dayExpires)
{
HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);
HttpContext.Current.Response.Cookies.Remove(key);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
public static string GetCookie(string key)
{
string value = string.Empty;
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
if (cookie != null)
{
// For security purpose, we need to encrypt the value.
HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
value = decodedCookie.Value;
}
else
{
SetCookie("currency", "GBP", 1);
if (key.ToUpper() == "CURRENCY")
value = "GBP";
else if (key.ToUpper() == "COUNTRYCODE")
value = "GB";
}
return value;
}
}
am able to store the cookie and also when i try to get the value of currency from the cookie using HttpContext.Current.Request.Cookies[key] where key has currency am getting the value as ""
in the image below you can have the look at the cookies stored
here you can see that you can currency repeated twice. In key [4] currency is "" where as i have my cookie value in key [6]. Any help why the currency is repeated twice when i am removing the key and then adding the key in the immediate lines.
For test purpose i have placed the set and get in the immediate lines. code below
CookieStore.SetCookie("currency", CurrencyCode, 1);
string currencycookie=CookieStore.GetCookie("currency");
Ultimately i must have only one currency where i have the unique key there.
Thanks.
Removing the key like this will not help you , remove the cookie set in the client browser. Either you have to set the expiry date in the past for the existing key. Better solution is to check if the key is available update the value of the cookie rather than removing and adding it.
if (Request.Cookies[key] != null)
{
Response.Cookies[key].Value = "NEW VAalue"
}
else
// create the new cookie key.
See my updated code with logic of removing and adding the new value
if (Request.Cookies["Test"] == null)
{
HttpCookie testCookie = new HttpCookie("Test");
testCookie.Value = "1";
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
}
else
{
var c = Request.Cookies["Test"];
c.Expires = DateTime.Now.AddDays(-10);
Response.Cookies.Add(c);
HttpCookie testCookie = new HttpCookie("Test");
testCookie.Value = "2";
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
}
I have updated your method.
public static void SetCookie(string key, string value, int dayExpires)
{
if (Request.Cookies[key] != null)
{
var c = HttpContext.Current.Request.Cookies[key];
c.Expires = DateTime.Now.AddDays(-10);
HttpContext.Current.Response.Cookies.Add(c);
}
HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
Related
I am trying to set a rememberMe cookie. It works however the domain it is being set to is using the subdomain as well as the main domain .... How can I set it to use just the main domain? I have tried rememberMeCookie.Domain = "MyNewDomain"; but then no cookie gets set.
I need the cookie to be set to the main domain in order for my rememberMe cookie to be read from another site as I am implementing a SSO procedure.
var rememberUrlSelection = Request.Cookies["rememberUrlSelection_" + Session["GuiId"]];
if (login.RememberMe || !login.RememberMe)
{
if (Request.Cookies["rememberMeWf"] == null)
{
HttpCookie rememberMeCookie = new HttpCookie("rememberMeWf");
var val = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(apiResp.Content);
string remC = Newtonsoft.Json.JsonConvert.SerializeObject(val.responseObject);
rememberMeCookie.Value = remC.UrlEncode();
rememberMeCookie.Expires = DateTime.Now.AddMonths(3);
rememberMeCookie.Domain = "MyNewDomain";
Response.Cookies.Add(rememberMeCookie);
}
}
You can try:-
cookie.Domain = Request.RequestUri.Host;
var rememberUrlSelection =
Request.Cookies["rememberUrlSelection_" + Session["GuiId"]];
if (login.RememberMe || !login.RememberMe) {
if (Request.Cookies["rememberMeWf"] == null) {
HttpCookie rememberMeCookie = new HttpCookie("rememberMeWf");
var val = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(
apiResp.Content);
string remC =
Newtonsoft.Json.JsonConvert.SerializeObject(val.responseObject);
rememberMeCookie.Value = remC.UrlEncode();
rememberMeCookie.Expires = DateTime.Now.AddMonths(3);
// rememberMeCookie.Domain = "MyNewDomain";
rememberMeCookie.Domain = Request.RequestUri.Host;
Response.Cookies.Add(rememberMeCookie);
}
}
I have an issue with ASP.NET cookies being lost between requests.
I have an ASCX control which has multiple filtering checkboxes. I can check/uncheck these checkboxes and then I click a . In this applyFilters method, I am setting cookies based on whether the checkboxes are checked/unchecked. The code that does this is :
public void setFilterCookie(string name, string val)
{
if (!String.IsNullOrEmpty(val) && (val != null && !val.Equals("-1")))
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
HttpCookie cookie = new HttpCookie(name, val);
cookie.Expires = DateTime.Now.AddDays(5);
response.Cookies.Add(cookie);
}
else
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
}
}
After the cookies are set, I want to databind a grid from the parent container of the control. In this databind method I am reading the cookies using the following method :
public string getCookie(string cookieName)
{
if (isNotNullOrEmpty(cookieName))
return request.Cookies[cookieName].Value.ToString().Trim();
else
return null;
}
The problem is that when I am setting the cookies, I can see the values being set (e.g. response.Cookies["Domain"] = "5") but when I am reading them the value is string empty.
Can somebody tell me what is wrong?
Thank you
You shouldn't be removing request cookies and adding response cookies with the same name multiple times. This should work.
public void setFilterCookie(string name, string val)
{
var cookieValue = string.Empty;
var expires = 0;
if (!string.IsNullOrWhiteSpace(val) && !val.Equals("-1"))
{
cookieValue = val;
expires = 5;
}
else
{
expires = -2;
}
var cookie = new HttpCookie(name, cookieValue) {Expires = DateTime.Now.AddDays(expires)};
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
I've accidentally jumped into the world of cookies and am trying to understand what's going on. I have a web app developed in Visual Studio 20120/C# using FormsAuthentication. When I first developed the app, I created a few fields to store in the authentication cookie: personID, firstName, and admin, the string looks like this: 777|Jimmy|1. Everything has worked well since then. Now I've added a fourth field to the end of the blur called "secBlur". When I do this and try to retrieve the value of secBlur, it tells me the array range is out of bounds because the earlier version of the cookie did not contain this field...makes sense. I've spent the past couple of days trying to rewrite the validity check for my cookie, and I thought I had everything figured out. However, when I go to write the new userData string into the cookie, it doesn't appear to be doing it. My code is below, I'll try to walk through what I'm doing...
In the page_load of my master page, the first thing I'm doing is making a call to a cookie class I created to check that the cookie is the correct version:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
authCookie ac = new authCookie();
ac.validate();
LoginName ct = (LoginName)loginStatus.FindControl("HeadLoginName");
if (ct != null)
{
formValues fv = new formValues();
ct.FormatString = fv.firstName;
}
}
}
My entire cookie class is below. In the Validate method I'm checking for the existence of the cookie and then checking to see that it is the correct version and that userData exists. If it's not the correct version or userData does not exist I call the getUserData method to retrieve the most current info for this year, create a new ticket, store the ticket into the cookie, and then save the cookie. I think the line saving the cookie is the problem, but I'm not sure.
using System;
using System.Data.SqlClient;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
namespace DMC.Classes
{
public class authCookie
{
public void cookiePrep(Login LoginUser)
{
string userData = "unknown|unknown";
// Concat the values into a single string to pass into the cookie
userData = getUserData(LoginUser.UserName);
// Create the cookie that contains the forms authentication ticket
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(LoginUser.UserName, LoginUser.RememberMeSet);
// Get the FormsAuthenticationTicket out of the encrypted cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(3,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
LoginUser.RememberMeSet,
userData,
ticket.CookiePath);
// Manually add the authCookie to the Cookies collection
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
string redirUrl = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, LoginUser.RememberMeSet);
if (redirUrl == null)
redirUrl = "../default.aspx";
HttpContext.Current.Response.Redirect(redirUrl);
}
public string getUserData(string userID)
{
string userData = "";
// Grab this user's firstname, personID, and Admin status
string mySQL = "exec get_adBasicInfo #userName";
string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(cf);
SqlCommand command = new SqlCommand(mySQL, connection);
command.Parameters.AddWithValue("#userName", userID);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
userData = string.Concat(dr["personID"], "|", dr["firstName"], "|", dr["secBlur"]);
}
dr.Close();
return userData;
}
public void validate()
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
/**********************************************************************************************************************
* Version 3: Added the secBlur field onto the userData string to see if logged in user needs to have sensitive *
* data blurred out (0: Normal; 1: Blur Sensitive Data *
**********************************************************************************************************************/
if ((ticket.Version != 3) || (ticket.UserData == ""))
{
string userData = getUserData(ticket.Name);
FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(3,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
ticket.IsPersistent,
userData,
ticket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newAuthTicket);
HttpContext.Current.Response.SetCookie(authCookie);
}
}
}
}
}
At this point control passes back out to the load_page function of my master page and attempts to retrieve the firstName of the user from the cookie by calling my formValues class, below:
using DMC.Classes;
using System.Web;
using System.Web.Security;
namespace DMC.Classes
{
public class formValues : System.Web.Services.WebService
{
public string firstName = getFirstName();
public string personID = getPersonID();
public string secBlur = getSecBlur();
private static string getUserDataString(int ix)
{
string retValue = "";
if (HttpContext.Current.Request.IsAuthenticated)
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (ticket != null)
{
string[] userData = { "" };
char[] delimiterChar = { '|' };
userData = ticket.UserData.Split(delimiterChar);
retValue = userData[ix];
}
}
}
return retValue;
}
private static string getFirstName()
{
string firstName = getUserDataString(1);
return firstName;
}
private static string getPersonID()
{
string personID = getUserDataString(0);
return personID;
}
private static string getSecBlur()
{
string secBlur = getUserDataString(2);
return secBlur;
}
}
}
On attempting to getFirstName, I'm getting an error in the getUserDataString method when attempting to set the retValue because the userData array is empty. So can somebody please tell me where I'm going wrong?
In my authCookie class, I changed from:
HttpContext.Current.Response.SetCookie(authCookie);
to
HttpContext.Current.Response.Add(authCookie);
I'm not a fan of this though, because from what I read, if the cookie already exists, this does not overwrite the cookie, it will just create a duplicate. But I've been playing around and it's the only thing that seems to work. If somebody has a better solution, please share!!
I want to store user latest visited pages in a cookie. It has 2 parts, PageTitle and URL.
I use the code below but it just save a value in first page load and don't change it in other page loads.
if (Request.Cookies["latestvisit"] == null)
{
HttpCookie myCookie = new HttpCookie("latestvisit");
myCookie.Expires = DateTime.Now.AddYears(1);
myCookie.Values[title] = System.Web.HttpUtility.UrlEncode(URL);
Response.Cookies.Add(myCookie);
}
else
{
System.Collections.Specialized.NameValueCollection cookieCollection = Request.Cookies["latestvisit"].Values;
string[] CookieTitles = cookieCollection.AllKeys;
//mj-y: If the url is reapeated, move it to end(means make it newer by removing it and adding it again)
string cookieURL = "";
foreach (string cookTit in CookieTitles)
{
cookieURL = System.Web.HttpUtility.UrlDecode(Request.Cookies["latestvisit"].Values[cookTit]);
if (cookieURL == URL)
{
cookieCollection.Remove(cookTit);
cookieCollection.Set(title, URL);
return;
}
}
//mj-y: If it was not repeated ...
if (cookieCollection.Count >15) // store just 15 item
cookieCollection.Remove(CookieTitles[0]);
cookieCollection.Set(title, URL);
}
and of course I want to code the url and decode it, so user cant determine the content of the cookie, how can I do it?
Try this:
if (Request.Cookies["latestVisit"] == null)
{
HttpCookie myCookie = new HttpCookie("latestVisit");
myCookie.Expires = DateTime.Now.AddYears(1);
myCookie.Values[title] = System.Web.HttpUtility.UrlEncode(URL);
Response.Cookies.Add(myCookie);
}
else
{
var myCookie = Request.Cookies["latestVisit"];
var cookieCollection = myCookie.Values;
string[] CookieTitles = cookieCollection.AllKeys;
//mj-y: If the url is reapeated, move it to end(means make it newer by removing it and adding it again)
string cookieURL = "";
foreach (string cookTit in CookieTitles)
{
cookieURL = System.Web.HttpUtility.UrlDecode(Request.Cookies["latestVisit"].Values[cookTit]);
if (cookieURL == URL)
{
cookieCollection.Remove(cookTit);
cookieCollection.Set(title, System.Web.HttpUtility.UrlEncode(URL));
Response.SetCookie(myCookie);
return;
}
}
//mj-y: If it was not repeated ...
cookieCollection.Set(title, System.Web.HttpUtility.UrlEncode(URL));
if (cookieCollection.Count > 15) // store just 15 item
cookieCollection.Remove(CookieTitles[0]);
Response.SetCookie(myCookie);
}
As a safe practice, I'd also recommend you to encode the title variable before adding it to the values collection, for example:
myCookie.Values[System.Web.HttpUtility.UrlEncode(title)]
= System.Web.HttpUtility.UrlEncode(URL);
and
cookieCollection.Set(System.Web.HttpUtility.UrlEncode(title),
System.Web.HttpUtility.UrlEncode(URL));
I am trying to set a cookie when the user access my webpage. The value of the cookie is a unique number that I store on my database to keep track of when the user comes back to my website. I set the cookie in my global.asax as follow:
void Application_BeginRequest()
{
string cookievalue = "";
string a = "";
try
{
a = GetCookie();
if (!string.IsNullOrEmpty(a))
{
cookievalue = a;
}
else
{
cookievalue = SetCookie();
}
}
catch (Exception ex)
{
}
}
In BeginRequest() I only want to check if the cookie exist. If exist, then do nothing and keep the value that is already inside the cookie. If it doesn't exist, then set the cookie and add a value.
public static string GetCookie()
{
string cookievalue = "";
try
{
if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
public static string SetCookie()
{
string cookievalue = "";
try
{
HttpCookie myCookie = new HttpCookie("TestCookie");
// Set the cookie value.
myCookie.Value = "1234"; //1234 is my unique number
myCookie.Expires = DateTime.Now.AddYears(50);
HttpContext.Current.Response.Cookies.Add(myCookie);
cookievalue = id;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
The problem is that everytime I reload the page, "TestCookie" gets rewritten with a new value. I have been reading the MSDN about how cookies are stored in ASP.NET and according to the instructions, the way it is supposed to work fine. I must be doing something wrong that I cannot see it. I had all this code inside a normal page e.g. test.aspx.cs to test it early but had the same result and decided to move it to the application level and see if that would make any difference but it did not :(.