C# 请求.Cookies和响应.Cookies之间的差异

C# 请求.Cookies和响应.Cookies之间的差异,c#,asp.net,.net,C#,Asp.net,.net,我在我的代码中多次使用这两种方法,但不知道它们的区别是什么,如果设置了cookie,那么请求和响应中的cookie不应该完全相同吗?请求是最新的还是响应 编辑: 好的,我得到了请求和响应之间的区别,但是如果我键入 string a = HttpContext.Current.Request.Cookie["a"].Value; 大多数情况下,它与 string a = HttpContext.Current.Response.Cookie["a"].Value; 但是我想知道使用这两种coo

我在我的代码中多次使用这两种方法,但不知道它们的区别是什么,如果设置了cookie,那么请求和响应中的cookie不应该完全相同吗?请求是最新的还是响应

编辑:

好的,我得到了请求和响应之间的区别,但是如果我键入

string a = HttpContext.Current.Request.Cookie["a"].Value;
大多数情况下,它与

string a = HttpContext.Current.Response.Cookie["a"].Value;

但是我想知道使用这两种cookie的区别是什么。

请求cookie是从客户端发送到服务器的内容(因此浏览器提供的内容)。响应cookie是您要放置在浏览器中的cookie。浏览器从响应对象接受cookie的下一个连接将在请求对象中提供cookie。

取决于上下文


Request是随每个http请求一起发送到服务器的数据。响应是服务器向客户端发出请求后的响应。

正如大家所说的
请求。Cookie
应该是来自客户端(浏览器)和
响应的Cookie。Cookie
是将发送回客户端(浏览器)的Cookie

当您将cookies添加到
Response
时,有一个黑魔法代码,它将值从
Response
cookies复制到
Request.cookies
。因此,看起来您在
请求
响应
中都有相同的cookie。请注意,这些复制的cookies不是来自客户端。。。所以要小心做出错误的决定

以下是有关代码讨论的链接:。特别是,以以下方式添加的cookies将显示在
请求中。cookies
集合中:

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

*从
Response.cookies
复制cookies的行为在文章中有记录:

使用
HttpResponse.Cookies
集合添加cookie后,即使响应尚未发送到客户端,cookie也会立即在
HttpRequest.Cookies
集合中可用

在Asp.net中,word用于将数据从服务器发送到客户端,而用于从客户端获取数据(以cookie、查询字符串的形式)等。 例如:

正如你提到的

string a = HttpContext.Current.Request.Cookie["a"].Value;
// I think this will check the cookie which is present in the client browser [ If client has sent the cookie to the server ]

string a = HttpContext.Current.Response.Cookie["a"].Value;
// and this will see the only Response object. If the cookie present in the response object then it will return you otherwise not.

差异是否应该是一个分号
?好的,假设那里有一个分号,我会放一个,我的意思是响应vs.请求-问题的标题显示了这一点。哦,奇怪,我可以发誓这两行都说了一段时间的请求。对不起,听起来更像是虫子而不是黑魔法。为什么会发生这种复制?@Gabrielburette-我已经添加了与您的相同的链接。如果您对实现特定行为的原因感兴趣-我不知道,您可以尝试提出单独的问题,但通常此类考古问题是不可回答的。如果您用新cookie替换现有cookie,
Request.Cookies[NAME]
将只返回其中一个cookie(根据经验,这似乎是请求cookie)。但是,如果您列举cookie,您将看到这两个cookie。
string a = HttpContext.Current.Request.Cookie["a"].Value;
// I think this will check the cookie which is present in the client browser [ If client has sent the cookie to the server ]

string a = HttpContext.Current.Response.Cookie["a"].Value;
// and this will see the only Response object. If the cookie present in the response object then it will return you otherwise not.