我的网站(针对客户端)发出警报,这些警报仅在用户每天第一次访问网站时显示,因此他们加载的第一个页面,生成的Cookie以及所有后续页面上都会显示,只要cookie存在(并且cookie上的日期与当前日期匹配),警报将不会显示。
网站上的某些页面使用https,例如捐赠页面。在这些页面上,警报始终显示。我认为这是因为cookie被阻止了。我该如何解决这个问题?这是我用于cookie的代码:
var cookie = HttpContext.Current.Request.Cookies["CHKD-Alert"];
// if cookie does not exist, create cookie
if (cookie == null)
{
HttpCookie alertCookie = new HttpCookie("CHKD-Alert");
alertCookie.Expires = DateTime.Now.AddDays(1d);
alertCookie["dateSet"] = DateTime.Now.Date.ToShortDateString();
HttpContext.Current.Response.SetCookie(alertCookie);
AlertStyle = "display: block;";
}
else
{
var dateSet = cookie["dateSet"];
// if alert has already been shown
if (cookie["dateSet"] != null && cookie["dateSet"] == DateTime.Now.Date.ToShortDateString())
{
AlertStyle = "display: none;";
}
else
{
AlertStyle = "display: block;";
Response.Cookies["CHKD-Alert"]["dateSet"] = DateTime.Now.Date.ToShortDateString();
}
}
ux_alerts.DataSource = alerts;
ux_alerts.DataBind();
编辑:我为HTTPS页面添加了第二个cookie:
var cookie = HttpContext.Current.Request.Cookies["CHKD-Alert"];
var secureCookie = HttpContext.Current.Request.Cookies["CHKD-Alert-Secure"];
// if cookie does not exist, create cookie
if (cookie == null)
{
HttpCookie alertCookie = new HttpCookie("CHKD-Alert");
alertCookie.Expires = DateTime.Now.AddDays(1d);
alertCookie["dateSet"] = DateTime.Now.Date.ToShortDateString();
HttpContext.Current.Response.SetCookie(alertCookie);
AlertStyle = "display: block;";
}
if (secureCookie == null)
{
HttpCookie alertCookieSecure = new HttpCookie("CHKD-Alert-Secure");
alertCookieSecure.Secure = true;
alertCookieSecure.Expires = DateTime.Now.AddDays(1d);
alertCookieSecure["dateSet"] = DateTime.Now.Date.ToShortDateString();
HttpContext.Current.Response.SetCookie(alertCookieSecure);
AlertStyle = "display: block;";
}
if (cookie != null || secureCookie != null)
{
var dateSet = cookie["dateSet"];
// if alert has already been shown
if ((cookie != null && cookie["dateSet"] != null && cookie["dateSet"] == DateTime.Now.Date.ToShortDateString()) ||
(secureCookie != null && cookie["dateSet"] != null && secureCookie["dateSet"] == DateTime.Now.Date.ToShortDateString()))
{
AlertStyle = "display: none;";
}
else
{
AlertStyle = "display: block;";
Response.Cookies["CHKD-Alert"]["dateSet"] = DateTime.Now.Date.ToShortDateString();
Response.Cookies["CHKD-Alert-Secure"]["dateSet"] = DateTime.Now.Date.ToShortDateString();
}
}
但警报仍会在首次加载HTTPS页面时显示。他们之后没有显示,这是一个改进,但我不希望他们第一次显示,如果网站上的另一个页面已被访问过。只要HTTP cookie存在,HTTPS cookie就应该存在
答案 0 :(得分:0)
在HttpCookie类的C#中有一个Secure属性,允许您通过HTTPS / SSL获取和设置cookie。我相信您需要设置条件来设置和获取这些HTTPS页面以及HTTP页面上的cookie。
通过HTTPS设置的Cookie应该只能通过HTTP工作,所以可能只需使用Secure创建一个cookie。听起来好像没有设置,默认情况下只在HTTP页面上设置cookie。