私は通常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;
}
}
これは私がそれを呼んでいる方法です、ここでそれはから読み取られているようにNULLRequest.QueryString["num"]
を返します:Cookie1
ActiveEmployee = new Employee() { Badge = "000000" };
Console.WriteLine(ActiveEmployee.Badge); // ActiveEmployee is NULL
...しかし、からの読み取りCookie1
もnullを返します。
Cookieの値をすぐに利用できるようにするために呼び出す必要のあるCommit()のようなコマンドはありますか?