How to store string in a cookie and retrieve it

前端 未结 2 1417
说谎
说谎 2021-02-01 22:16

I want to store the username in the cookie and retrieve it the next time when the user opens the website. Is it possible to create a cookie which doesnt expires when the browser

2条回答
  •  轮回少年
    2021-02-01 23:03

    Writing a cookie

    HttpCookie myCookie = new HttpCookie("MyTestCookie");
    DateTime now = DateTime.Now;
    
    // Set the cookie value.
    myCookie.Value = now.ToString();
    // Set the cookie expiration date.
    myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire
    
    // Add the cookie.
    Response.Cookies.Add(myCookie);
    
    Response.Write("

    The cookie has been written.");

    Reading a cookie

    HttpCookie myCookie = Request.Cookies["MyTestCookie"];
    
    // Read the cookie information and display it.
    if (myCookie != null)
       Response.Write("

    "+ myCookie.Name + "

    "+ myCookie.Value); else Response.Write("not found");

提交回复
热议问题