Cookie没有快速设置

jp2*_*ode 2 c# asp.net cookies httpcookie

我通常不使用Cookie,但我想查看这个通常使用的Session变量.

如果我设置了Cookie,那么请立即尝试从中读取,我没有得到我刚刚设置的值.

但是,如果我刷新页面或关闭浏览器并将其重新打开,则Cookie似乎已设置.

我正在Chrome中调试它.那会有什么不同吗?

public const string COOKIE = "CompanyCookie1";
private const int TIMEOUT = 10;

private string Cookie1 {
  get {
    HttpCookie cookie = Request.Cookies[COOKIE];
    if (cookie != null) {
      TimeSpan span = (cookie.Expires - DateTime.Now);
      if (span.Minutes < TIMEOUT) {
        string value = cookie.Value;
        if (!String.IsNullOrEmpty(value)) {
          string[] split = value.Split('=');
          return split[split.Length - 1];
        }
        return cookie.Value;
      }
    }
    return null;
  }
  set {
    HttpCookie cookie = new HttpCookie(COOKIE);
    cookie[COOKIE] = value;
    int minutes = String.IsNullOrEmpty(value) ? -1 : TIMEOUT;
    cookie.Expires =  DateTime.Now.AddMinutes(minutes);
    Response.Cookies.Add(cookie);
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是我如何使用它:

public Employee ActiveEmployee {
  get {
    string num = Request.QueryString["num"];
    string empNum = String.IsNullOrEmpty(num) ? Cookie1 : num;
    return GetActiveEmployee(empNum);
  }
  set {
    Cookie1 = (value != null) ? value.Badge : null;
  }
}
Run Code Online (Sandbox Code Playgroud)

这就是我调用它的方式,其中Request.QueryString["num"]返回NULL以便Cookie1从中读取:

ActiveEmployee = new Employee() { Badge = "000000" };
Console.WriteLine(ActiveEmployee.Badge); // ActiveEmployee is NULL
Run Code Online (Sandbox Code Playgroud)

...但是阅读Cookie1也会返回null.

是否需要调用Commit()之类的命令才能立即获得cookie值?

Chr*_*ain 6

Cookie与Session不同 - 有两个 cookie集合,而不是一个.

Request.Cookies != Response.Cookies.前者是在浏览器请求页面时从浏览器发送的一组cookie,后者是您使用内容发回的内容.这暴露了Cookie RFC的本质,与Session不同,Session是纯粹的Microsoft构造.


Kir*_*oll 5

当您在响应中设置cookie时,它不会被神奇地传输到请求 cookie集合中.它在响应中,你可以在那里检查它,但它不会出现在请求对象中,直到它在下一个请求中实际从浏览器发送.