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 request going to the the most up to date , or response?
EDIT:
ok , I get the difference between a request and a response, but if I type
string a = HttpContext.Current.Request.Cookie["a"].Value;
it is most of the time the same as
string a = HttpContext.Current.Response.Cookie["a"].Value;
but I am wondering what is the difference between using the two.
Focus at Server, Request is message that arrive to server for request something. Response is message that send from server to client for give thing that client what.
The Set-Cookie header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. The Cookie header is included by the client application with an HTTP request sent to a server, if there is a cookie that has a matching domain and path.
No. Not every request sends the cookies. It depends on the cookie configuration and client-server connection. For example, if your cookie's secure option is set to true then it must be transmitted over a secure HTTPS connection.
Also I would say it is perfectly acceptable to change or set a cookie in response for the GET request because you just return some data.
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 theHttpRequest.Cookies
collection, even if the response has not been sent to the client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With