[英]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.我在 C# 中生成一个 cookie,并尝试在页面加载时以 ascx 的形式在 JQuery 中读取它。 The site is a mad mixture of MVC and ANgularJS, but in this instance I'm purely looking in the ascx.该站点是 MVC 和 ANgularJS 的疯狂混合,但在这种情况下,我纯粹是在 ascx 中查找。 The site runs in https.该站点运行于 https。
C# cookie generation: C# cookie 生成:
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:尝试以 ascx 读取 cookie:
<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.我检查了开发工具,cookie 就在那里。
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.这个解决方案更好,因为您不必遍历所有 cookies。我在浏览器中的私有 window 中测试了这个。
More ways of getting cookies by value:按值获取 cookies 的更多方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.