代码之家  ›  专栏  ›  技术社区  ›  Vikas

如何在asp.net中创建持久Cookie?

  •  63
  • Vikas  · 技术社区  · 14 年前

    我正在创建具有以下行的cookies:

    HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
    userid.Expires.AddYears(1);
    Response.Cookies.Add(userid);
    

    我怎样才能让它持久?

    如果我在关闭浏览器后再次访问同一页,我将无法取回它。

    6 回复  |  直到 4 年前
        1
  •  104
  •   this. __curious_geek    14 年前

    你可以这样做。

    //create a cookie
    HttpCookie myCookie = new HttpCookie("myCookie");
    
    //Add key-values in the cookie
    myCookie.Values.Add("userid", objUser.id.ToString());
    
    //set cookie expiry date-time. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddHours(12);
    
    //Most important, write the cookie to client.
    Response.Cookies.Add(myCookie);
    

    正在读取持久cookie。

    //Assuming user comes back after several hours. several < 12.
    //Read the cookie from Request.
    HttpCookie myCookie = Request.Cookies["myCookie"];
    if (myCookie == null)
    {
        //No cookie found or cookie expired.
        //Handle the situation here, Redirect the user or simply return;
    }
    
    //ok - cookie is found.
    //Gracefully check if the cookie has the key-value as expected.
    if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
    {
        string userId = myCookie.Values["userid"].ToString();
        //Yes userId is found. Mission accomplished.
    }
    
        2
  •  52
  •   Peter O. Manuel Pinto    9 年前

    虽然接受的答案是正确的,但它没有说明原始代码无法工作的原因。

    HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
    userid.Expires.AddYears(1);
    Response.Cookies.Add(userid);
    

    看看第二行。过期的依据是Expires属性,该属性包含默认值1/1/0001。以上代码的计算结果为1/1/0002。此外,计算结果不会保存回该属性。相反,Expires属性应该以当前日期为基础进行设置。

    更正代码:

    HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
    userid.Expires = DateTime.Now.AddYears(1);
    Response.Cookies.Add(userid);
    
        3
  •  26
  •   oalbrecht    10 年前

    FWIW在未加密的cookie中存储像userid这样的东西时要非常小心。这样做会使你的网站很容易出现cookie中毒,用户可以很容易地模仿另一个用户。如果您正在考虑这样的事情,我强烈建议您直接使用表单验证cookie。

    bool persist = true;
    
    var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
    
    cookie.Expires = DateTime.Now.AddMonths(3);
    
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    
    var userData = "store any string values you want inside the ticket
                     extra than user id that will be encrypted"
    
    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
         ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
    
    cookie.Value = FormsAuthentication.Encrypt(newTicket);
    
    Response.Cookies.Add(cookie);
    

    string userId = null;
    if (this.Context.User.Identity.IsAuthenticated) 
    {
        userId = this.Context.User.Identity.Name;
    }
    
        4
  •  2
  •   Kate    9 年前

    据我所知,您使用ASP.NET身份验证并要设置cookies持久性,您需要设置FormsAuthenticationTicket.IsPersistent=true

    bool isPersisted = true;
    var authTicket = new FormsAuthenticationTicket(
    1,
    user_name, 
    DateTime.Now,
    DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
    isPersisted,//THIS IS THE MAIN FLAG
    addition_data);
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
        if (isPersisted)
            authCookie.Expires = authTicket.Expiration;
    
    HttpContext.Current.Response.Cookies.Add(authCookie);
    
        5
  •  0
  •   Robert Williams    14 年前

    HttpContext.Current.Response.Cookies.Add(userid);
    

    当您需要读取cookie的值时,可以使用类似以下的方法:

        string cookieUserID= String.Empty;
    
        try
        {
            if (HttpContext.Current.Request.Cookies["userid"] != null)
            {
                cookieUserID = HttpContext.Current.Request.Cookies["userid"];
            }
        }
        catch (Exception ex)
        {
           //handle error
        }
    
        return cookieUserID;
    
        6
  •  0
  •   Diganta Kumar    12 年前

    //添加cookie

    var panelIdCookie = new HttpCookie("panelIdCookie");
    panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
    panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
    Response.Cookies.Add(panelIdCookie);
    

    //读取cookie

        var httpCookie = Request.Cookies["panelIdCookie"];
                    if (httpCookie != null)
                    {
                        panelId = Convert.ToInt32(httpCookie["panelId"]);
                    }