【问题标题】:Difference between Request.Cookies and Response.CookiesRequest.Cookies 和 Response.Cookies 之间的区别
【发布时间】:2012-08-03 17:10:42
【问题描述】:

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

编辑:

好的,我知道请求和响应之间的区别,但是如果我输入

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

大部分时间都和

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

但我想知道使用两者有什么区别。

【问题讨论】:

  • 只是分号;的区别吗?
  • 好的,假设那里有一个分号,我会放一个,我的意思是响应与请求 - 问题标题显示
  • 哦,奇怪,我可以发誓这两行都说请求一段时间。对不起。

标签: c# asp.net .net


【解决方案1】:

正如大家所说,Request.Cookies 应该是来自客户端(浏览器)的 cookie,Response.Cookies 是发送回客户端(浏览器)的 cookie。

当您将 cookie 添加到 Response 时,有 black magic 有据可查的*代码将值从 Response cookie 复制到 Request.Cookies。结果,看起来您在 RequestResponse 中都有相同的 cookie。请注意,这些复制的 cookie 并非来自客户端……所以要小心做出错误的决定。

这里是讨论代码的链接:http://forums.asp.net/t/1279490.aspx。特别是,通过以下方式添加的 cookie 将显示在 Request.Cookies 集合中:

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

*从 Response.Cookies 复制 cookie 的行为记录在 HttpResponse.Cookies 文章中:

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

【讨论】:

  • 这听起来更像是一个错误而不是黑魔法。为什么会发生这种复制?
  • @GabrielBurete - 我添加了与您的original question 相同的链接。如果您对实施特定行为的原因感兴趣 - 我不知道,您可以尝试提出单独的问题,但通常此类考古问题被关闭为不可回答。
  • 如果您用新的 cookie 替换现有的 cookie,Request.Cookies[NAME] 将只返回一个 cookie(根据经验,这似乎是请求 cookie)。但是,如果您枚举 cookie,您将看到这两个 cookie。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    Response.Write("will write the content on the form which will return to the client");
    // Response.Cookies will send the cookie to the client browser.
     Response.Cookies.Add(HttpCookie("MyCookie", "MyValue"))
    //and Request.Cookies is used to get the cookie value which is already present in the clinet browswer   
    

    正如你所说的

    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.
    

    【讨论】:

      【解决方案4】:

      取决于什么上下文。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 2020-05-10
        • 2014-09-20
        相关资源
        最近更新 更多