I have set a cookie on the controller:
HttpCookie loggedIn = new HttpCookie("LoggedIn", "true");
Request.Cookies.Add(loggedIn);
I am trying to access this on document ready?
$( document ).ready(function() {
if ('#Request.Cookies["LoggedIn"]' != null) {
var loggedIn = '#Request.Cookies["LoggedIn"].Value';
console.log("Logged In " + loggedIn);
}
});
This keeps coming through as null?
Any ideas?
You're not actually accessing the cookie from the client-side JavaScript. Even though you're sending the cookie back to the browser, your code is ignoring that cookie and trying to access it via a Razor expansion. I guess that could work, but it seems like a roundabout way to do it.
You can access cookies from JavaScript though the document.cookie property, which is a ; delimited list of cookies.
Since you're using jQuery, a simpler way is to use the jquery.cookie plugin.
var loggedIn = $.cookie('LoggedIn');
Update: I just realized you're setting the cookie in the request. You should be setting it in the response:
Response.SetCookie(loggedIn);
Related
Let's say I have a cookie with value "OLD", then I update the cookie with following code :
var lang = new HttpCookie("lang");
lang.Value = "NEW";
lang.Expires = DateTime.UtcNow.AddDays(2);
HttpContext.Current.Response.SetCookie(lang); //set updated cookie value
var x = HttpContext.Current.Request.Cookies("lang");
x will still have "OLD" as value because it's not being sent to the client. Is it possible to get the updated value without it being sent to client first?
The Problem
you are setting the cookie in HttpContext.Current.Response and trying to find it in HttpContext.Current.Request even before the next request has come to server.
It is not going to work.
My Advice
For this case, use of cookie is incorrect. You have other options better fit for purpose, like -
ViewData
ViewBag
TempData
Session
ViewModel
The Answer
But if you still want to use cookie this way, search the cookie in HttpContext.Current.Response. I am sure you will get it.
Like this:
var cookieValue = HttpContext.Current.Response.Cookies["OLD"].Value
If you don't want to send value to client side and only want to use for reference you can use TempData for your purpose. Which might help.
I think, you should look for it in Response, not in Request, because request - it's that came from client.
Okay so this one has me stumped. I have written a function that reads the value of a cookie. The logic is
check Response.Cookies in case it has just been written
otherwise read from Request.Cookies to get the previous value
If the cookie has just been written then all is good, and I get the value. However if the cookie has not been written on this visit - it appears to blank the value of the already store cookie.
What?
Here is the code
Note the write happens in a controller
public static void PersistCookie(string cookieName, string cookieValue, bool persistent)
{
var cookie = new HttpCookie(cookieName, cookieValue)
{
Path = "/",
HttpOnly = true,
};
if (persistent)
cookie.Expires = DateTime.Now.AddMonths(6);
HttpContext.Current.Response.SetCookie(cookie);
}
Note the read happens ina partial view
public static string ReadCookieValue(string cookieName, bool checkResponseFirst)
{
if (checkResponseFirst && HttpContext.Current.Response.Cookies[cookieName] != null &&
HttpContext.Current.Response.Cookies[cookieName].Value.HasValue())
return HttpContext.Current.Response.Cookies[cookieName].Value;
return HttpContext.Current.Request.Cookies[cookieName] != null ? HttpContext.Current.Request.Cookies[cookieName].Value : "";
}
It almost seems that just by checking if a cookie has a value, it messes things up.
Thoughts?
Okay so after much more searching on the web, a good work colleague cam up with the following
it looks like I have come across a curiosity in .NET.
Check out this article
http://www.codeproject.com/Articles/3106/On-The-Care-and-Handling-of-Cookies
If you try to access a cookie that doesn't exist in the Response.Cookies collection, it will be created with an empty string in the Value and an Expires date of 01-Jan-0001 00:00. Strangely, it also creates a matching cookie in the Request.Cookies collection if one doesn't already exist.
So if you look at a cookie in the Response then you are indirectly overwriting the cookie on the client machine with an empty cookie, due to expire when the browser closes
So my problem is solved (or should that be unsolvable). As it turns out I have a workaround using the ViewBag but I am glad I was not going crazy!
Thanks for you help
I am not sure you can set cookies in partial views. When setting the cookie with Response.SetCookie, the information is returned to the browser in the Set-Cookie HTTPHeader field. I don't think partial views can set this value, try inspecting your applications response with Fiddler2, after calling Response.SetCookie.
I usually set my cookies with plain Javascript.
I need to delete authentication cookie manually (Instead of using FormsAuthentication.SignOut whcih for some reasons does not work). I tried
System.Web.HttpContext.Request.Cookies.Remove(cookieName); // for example .ASPXAUTH
System.Web.HttpContext.Response.Cookies.Remove(cookieName); // for example .ASPXAUTH
FormsAuthentication.SignOut(); // I don't know why this one does not work
Neither of those command work. In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.
Try:
if (Request.Cookies["MyCookie"] != null)
{
var c = new HttpCookie("MyCookie")
{
Expires = DateTime.Now.AddDays(-1)
};
Response.Cookies.Add(c);
}
More information on MSDN.
c.Expires = DateTime.Now.AddDays(-1);
This does not clear cookies instantly.
Use this: c.Expires = DateTime.Now.AddSeconds(1);
This will clear cookies instantly.
I am using c# and mvc. I am trying to write a cookie to the user browser. But after a refresh of the browser the cookie disappears.
This is my code for writing the cookie:
movieCookie = new HttpCookie(cookieName);
movieCookie.Value = "test;
movieCookie.Expires = DateTime.Now.AddDays(30);
//add the cookie
HttpContext.Current.Response.Cookies.Add(movieCookie);
and the one for reading the cookie:
//check if such cookie exist
HttpCookie movieCookie = null;
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
movieCookie = HttpContext.Current.Request.Cookies[cookieName];
Another thing to add is that when I searched "AllKeys" like so:
HttpContext.Current.Request.Cookies.AllKeys
it shows an empty string array, for some reason.
any ideas?
Some possibly silly questions
Check your web-servers time and date, are they set correctly, if they are (in your case) 2 years out it will expire cookies immediately.
Check that cookieName is the same
Check that after setting the cookie to the response your not redirecting before the cookie is set. For a cookie to be set you need to set headers and push them out.
I solved it. It appears that in MVC the "return view" after the cookie creation, cause the cookie not to be saved.
Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:
private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).
It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.
Now for the part that drives me nuts.
Here is the JavaScript function I am using to delete the cookie:
function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
So, of course, at some point after the cookie is set, I delete it like so:
deleteCookie("MyCookie");
Only, that doesn't do the job; the cookie still exists. So, anyone know why?
you have to delete your cookie at the same path where you created it.
so create your cookie with path=/ and delte it with path=/ as well..
Have you checked the client-side and server-side cookie domains and paths to ensure they're the same?
Is one cookie secure and the other not?
Other than that, I would suspect server/client clock sync issues, as Erlend suggests.
Weird.. The code you pasted is almost verbatim to this: http://www.quirksmode.org/js/cookies.html which works fine..
I know you are using Ajax, but have you tried quickly knocking it to server side code to see if that works? This may help in figuring if it is a problem with the JS or something else (e.g mystery file locking on the cookie)?
Update
Just had a quick Google, looks like there may be issues with browser settings as well. I don't think your problem is the code here, it's more likely to be something else. I would suggest try the above as PoC and we can move from there. :)
I posted a js cookie util a week or so ago on my blog. This has worked for me on all "A Grade" browsers.
var CookieUtil = {
createCookie:function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie:function(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
eraseCookie:function(name) {
createCookie(name,"",-1);
}
};
Have you tried to use ;expires=Thu, 01-Jan-1970 00:00:01 GMT?
Also if a cookie domain was specified during the creation, I've found that you must also specify the cookie domain while trying to delete (expire) it.
Are we sure there's no code that sets the Cookie to HttpOnly (we're not missing anything above)? The HttpOnly property will stop (modern) browsers from modifying the cookie. I'd be interested to see if you can kill it server side like Rob suggests.
I assume you are calling this javascript on the browser side. Which browser are you using, how are you viewing the cookie to confirm it is still there?