我通常不使用 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);
}
}
下面是我如何使用它:
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;
}
}
这就是我的调用方式,其中Request.QueryString["num"]
返回NULL以便Cookie1
从中读取:
ActiveEmployee = new Employee() { Badge = "000000" };
Console.WriteLine(ActiveEmployee.Badge); // ActiveEmployee is NULL
...但读取 fromCookie1
也返回 null 。
我需要调用像 Commit() 这样的命令,以便立即使用 cookie 值吗?