c# cookie不会立即刷新cookie
本文关键字:cookie 刷新 | 更新日期: 2023-09-27 18:04:30
我目前在我的Web应用程序中有一个cookie问题。
首先,我在我的控制器中创建了2个泛型方法来简化我的cookie操作。如下:
public bool SetCookie<T>(string key, T value)
{
try
{
string str = Utils.JSONParser.Serialize(value);
var cookie = new HttpCookie(key, Utils.JSONParser.Serialize(value))
{
HttpOnly = true
};
cookie.Expires = DateTime.UtcNow.AddDays(365);
Response.SetCookie(cookie);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public T GetCookie<T>(string key)
{
T obj;
if (Request.Cookies[key] != null)
{
HttpCookie cookie = Request.Cookies.Get(key);
obj = Utils.JSONParser.Deserialize<T>(cookie.Value);
return obj;
}
return (typeof(T) == typeof(int) ? (T)(object)-1 : default(T));
}
请注意,这些方法在一些"正常"使用下可以完美地工作。(跑龙套。JSONParser是JavaScriptSerializer的简单封装。
我使用这个代码有一个问题:
public ActionResult Index(int LineNumber = -1)
{
IndexViewModel model = new IndexViewModel();
if (LineNumber != -1)
this.SetCookie("lineNumber", LineNumber);
model.LineNumber = this.GetCookie<int>("lineNumber");
....
}
例如,LineNumber
的值为5,当前cookie值为(例如)20。这里我要擦掉20,用5代替。但这并没有发生。我必须通过这个方法2次(5作为参数),最终在cookie值中存储5。
所以我的问题是,是否有加载时间来存储cookie ?这怎么解释呢?或者我只是错过了什么?
注意您的SetCookie
方法如何改变响应,而您的GetCookie
方法从您的请求中获取值。因此,只有当您完成整个请求处理然后获得第二个请求时,请求中设置的cookie才会是您在第一个响应中设置的cookie。