Difference between Request.Cookies and Response.Cookies

前端 未结 4 2032
孤街浪徒
孤街浪徒 2021-01-31 15:16

I use both of these many times in my code and don\'t really know what the difference is , if a cookie is set shouldn\'t it be exactly the same in request and response? and is re

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 16:06

    As everyone says Request.Cookies are supposed to be cookies coming from client (browser) and Response.Cookies are cookies that will be send back to client (browser).

    There is black magic well documented* code that copies values from Response cookies to Request.Cookies when you add cookies to Response. As result it looks like you have same cookies in both Request and Response. Note that these copied cookies did not come from the client... so beware of making wrong decisions.

    Here is a link to discussion about the code: http://forums.asp.net/t/1279490.aspx. In particular, cookies added in the following way will show up in the Request.Cookies collection:

    Response.Cookies.Add(HttpCookie("MyCookie", "MyValue"))
    

    *The behavior of cookies getting copied from Response.Cookies is documented in the HttpResponse.Cookies article:

    After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.

提交回复
热议问题