C#饼干不会立即刷新饼干
我目前在我的Web应用程序中遇到cookie问题 首先,我在控制器中创建了两个通用方法,以简化cookie操作。这是:C#饼干不会立即刷新饼干,c#,cookies,C#,Cookies,我目前在我的Web应用程序中遇到cookie问题 首先,我在控制器中创建了两个通用方法,以简化cookie操作。这是: public bool SetCookie<T>(string key, T value) { try { string str = Utils.JSONParser.Serialize(value); var cookie = new HttpCookie(key, U
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));
}
public bool SetCookie(字符串键,T值)
{
尝试
{
string str=Utils.JSONParser.Serialize(值);
var cookie=newhttpcookie(key,Utils.JSONParser.Serialize(value))
{
HttpOnly=true
};
cookie.Expires=DateTime.UtcNow.AddDays(365);
SetCookie(cookie);
返回true;
}
捕获(例外情况除外)
{
掷骰子;
}
}
公共T GetCookie(字符串键)
{
T-obj;
if(Request.Cookies[key]!=null)
{
HttpCookie cookie=Request.Cookies.Get(key);
obj=Utils.JSONParser.Deserialize(cookie.Value);
返回obj;
}
return(typeof(T)==typeof(int)?(T)(object)-1:默认值(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");
....
}
公共操作结果索引(int LineNumber=-1)
{
IndexViewModel model=新的IndexViewModel();
如果(行号!=-1)
此.SetCookie(“行号”,行号);
model.LineNumber=this.GetCookie(“LineNumber”);
....
}
这里,LineNumber
的值是例如5,当前cookie值是(例如)20。所以,这里我想擦除20,然后放5。但是这没有发生。我必须通过此方法两次(以5为参数)才能最终将5存储在cookie值中
所以我的问题是,是否有一个加载时间来存储cookie?这可以解释这一点?或者我只是缺少了什么?请注意
SetCookie
方法如何更改响应,而GetCookie
方法从您的请求中获取值。因此,只有当您完成整个请求处理并获得se时cond request请求中设置的cookie将是您在第一次响应中设置的cookie。您可能要寻找的答案在这里。现在您这么说似乎有点愚蠢……x)。但我想你是对的!非常感谢你,伙计!别担心,我也犯过同样的错误