When to use Request.Cookies over Response.Cookies?

后端 未结 6 579
囚心锁ツ
囚心锁ツ 2020-12-02 07:30

Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processi

6条回答
  •  温柔的废话
    2020-12-02 08:08

    They are 2 different things, one SAVES [Response], the other READS [Request]

    in a Cookie (informatics speaking) :) you save a small file for a period of time that contains an object of the type string

    in the .NET framework you save a cookie doing:

    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.AddMinutes(1);
    
    // Add the cookie.
    Response.Cookies.Add(myCookie);
    
    Response.Write("

    The cookie has been written.");

    You wrote a cookie that will be available for one minute... normally we do now.AddMonth(1) so you can save a cookie for one entire month.

    To retrieve a cookie, you use the Request (you are Requesting), like:

    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");

    Remember:

    To Delete a Cookie, there is no direct code, the trick is to Save the same Cookie Name with an Expiration date that already passed, for example, now.AddMinutes(-1)

    this will delete the cookie.

    As you can see, every time that the time of life of the cookie expires, that file is deleted from the system automatically.

提交回复
热议问题