Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Request.Cookies and Response.Cookies

Tags:

c#

.net

asp.net

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.

like image 989
Scott Selby Avatar asked Aug 03 '12 17:08

Scott Selby


People also ask

What are the major differences between request and response messages?

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.

How are request cookies set?

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.

Are cookies sent automatically with every request?

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.

Can you set cookies with a GET request?

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.


1 Answers

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.

like image 195
Alexei Levenkov Avatar answered Sep 21 '22 18:09

Alexei Levenkov