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.