store user latest visit pages in cookie - c#

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

Related

How To generate cookie in C# and read with JS in MVC through HTTPS

I'm generating a cookie in C#, and attempting to read it in JQuery in an ascx on page load. The site is a mad mixture of MVC and ANgularJS, but in this instance I'm purely looking in the ascx. The site runs in https.
C# cookie generation:
private void UpdateSessionTimerCookie(bool? loggedIn = true)
{
#region Not Logged in? Return nothing
var isLoggedIn = loggedIn ?? false;
if (!isLoggedIn) { return; }
#endregion
const string cookieName = "sRoller";
#region Delete the cookie if it already exists
if (Request.Cookies.Exists(cookieName) && Request.Cookies[cookieName] != null)
{
Response.Cookies.Remove(cookieName);
Request.Cookies.Remove(cookieName);
}
#endregion
#region Build the new cookie (reset of timer)
var cookie = new HttpCookie(cookieName)
{
HttpOnly = false,
SameSite = SameSiteMode.Lax,
Expires = DateTime.Now.AddMinutes(HttpContext.Session.Timeout),
Value = DateTime.Now.ToString(),
Path = "/",
Secure = true,
Shareable = false
};
Response.Cookies.Add(cookie);
Response.SetCookie(cookie);
#endregion
}
Attempted cookie read in ascx:
<script type="text/javascript">
$(document).ready(function() {
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return "";
}
var myCookie = getCookie("sRoller");
//first alert
alert(myCookie);
});
function ShowCookie() {
var MyCookie = getCookieValue("sRoller");
//second alert
alert(MyCookie);
}
function getCookieValue(name) {
var cookieList = document.cookie.split('; ');
var cookies = {};
for (var i = cookieList.length - 1; i >= 0; i--) {
var cookie = cookieList[i].split('=');
cookies[cookie[0]] = cookie[1];
}
return cookies[name];
}
ShowCookie();
</script>
In the first alert, I get "undefined". In the second alert, I get nothing.
I've checked dev tools, and the cookie is there.
Try this:
function getCookieValue(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
This solution is better, because you do not have to iterate over all cookies. I tested this in a private window in my browser.
More ways of getting cookies by value:
Get cookie by name

Setting a Cookie in C#

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

ASPX Cookies lost

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

How to remove cookie from server side in c#

I have an asp.net mvc 4 project where try to update my cookie, but instead of this it's create another cookie, and for example I have a 3 duplicate cookies with name "page". Anybody know how to fix this?
if (page != null && Request.Browser.Cookies) {
if (Response.Cookies.AllKeys.Contains("page")) {
var aCookie = new HttpCookie("page") { Expires = DateTime.Now.AddDays(-1) };
Response.Cookies.Add(aCookie);
}
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
If you want to remove your cookie from client, you should set it as expired:
if (page != null && Request.Browser.Cookies) {
Response.Cookies.Remove("page");
var aCookie = new HttpCookie("page") { Expires = DateTime.Now.AddDays(-1) };
Response.Cookies.Add(aCookie);
}
But if you only need to update it, just remove it from response and add a new version of it:
if (page != null && Request.Browser.Cookies) {
Response.Cookies.Remove("page");
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
Have you tried removing the cookie before adding the new one.
if (page != null && Request.Browser.Cookies)
{
Response.Cookies.Remove("page");
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
Note that Response.Cookies.Remove("page") will not throw an exception if the is no page cookie, so testing for its existence is not required.

Cannot retrieve cookie value

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

Categories

Resources