Bool HttpCookie重定向到登陆页面无法成功运行

时间:2017-01-24 13:03:52

标签: c# asp.net

我一直在编写一个脚本来将用户发送到目标网页,前提是他们今天还没有使用HttpCookie看到它:

bool userVisited = false;
HttpCookie cookie = Request.Cookies["Hoarding"];
if (cookie == null)
{
   cookie = new HttpCookie("Hoarding");
   cookie.Values.Add("userVisitedSplash", "true");
   cookie.Expires = DateTime.Now.AddDays(1);
   cookie.HttpOnly = true;
   this.Page.Response.AppendCookie(cookie);
} 
else 
{
    if (!Boolean.TryParse(cookie.Values["userVisitedSplash"], out userVisited)) 
    {
        userVisited = false;
    }
    else 
    {
        Response.Redirect("/default-splash.aspx");
    }
}

此代码重定向成功,但在目标网页上按下ENTER SITE后,它会再次重定向到启动画面。没有考虑到它已经访问过它。

这里有什么明显的错误吗?

1 个答案:

答案 0 :(得分:2)

你可以试试这个吗?

 bool userVisited = false;
        HttpCookie cookie = Request.Cookies["Hoarding"];
        if (cookie == null)
        {
            cookie = new HttpCookie("Hoarding");
            cookie.Values.Add("userVisitedSplash", "true");
            cookie.Expires = DateTime.Now.AddDays(1);
            cookie.HttpOnly = true;
            this.Page.Response.AppendCookie(cookie);
            Response.Redirect("/default-splash.aspx");
        }
        else
        {
            if (Boolean.TryParse(cookie.Values["userVisitedSplash"], out userVisited))
            {
                if (!userVisited)
                {
                    Response.Redirect("/default-splash.aspx");
                }

            }
            else
            {
                Response.Redirect("/default-splash.aspx");
            }
        }