我目前在网络应用程序中遇到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));
}
请注意,这些方法与某些“正常”使用完美配合。 (Utils.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作为参数)最终将5存储在cookie值中。
所以我的问题是,是否有加载时间存储cookie?哪个会解释这个?或者我只是错过了什么?
答案 0 :(得分:2)
注意当GetCookie
方法从您的请求中获取值时,Import-CSV
方法如何更改响应。因此,只有当您完成整个请求处理然后获得第二个请求时,请求中设置的cookie才会是您在第一个响应中设置的cookie。