我有以下代码设置cookie:
string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue;
HttpCookie cookie = new HttpCookie("localization",locale);
cookie.Expires= DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试读取cookie时,Value为Null.cookie存在.如果检查我永远不会超过以下:
if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))
Run Code Online (Sandbox Code Playgroud)
救命?
在我的应用程序中 有一个登录机制,用于保存一个cookie,其中包含刚刚登录的用户的信息
private void CreateCookie(LoginEventArgs args)
{
HttpCookie cookie = new HttpCookie("user");
cookie.Values["name"] = args.User_Name;
cookie.Values["id"] = args.ID;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
Run Code Online (Sandbox Code Playgroud)
在我的母版页面加载我执行检查以查看此cookie是否存在:
HttpCookie cookie = Request.Cookies["user"] ;
if( (cookie != null) && (cookie.Value != ""))
{
if (Session["user"] == null)
Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
}
Run Code Online (Sandbox Code Playgroud)
现在如果我登录(创建一个cookie),关闭浏览器,然后运行我的应用程序.再次,cookie存在,它的值是正确的,用户"自动"登录.
如果我首先从启动内容页面重定向到不同的内容页面,则cookie值也完好无损,
问题是当我第二次重定向回另一个内容页面时,主页面加载,检查cookie是否存在但是值被删除...
关于为什么会这样的想法?
也许我退出的方式可能是这个问题的原因:
当我注销时,我创建一个与1天前相同名称的cookie.
private void Remove_Cookie()
{
HttpCookie cookie = new HttpCookie("user");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Run Code Online (Sandbox Code Playgroud)
在iv'e描述我没有正式退出的情况下,我只是结束我的应用程序,所以这不应该有任何影响.