使用cookie获取用户信息,长时间不用重新登录

melon23 2015-04-09 03:24:53
在login页面:
SaveCookie(FormsAuthentication.GetAuthCookie(model.UserName, false), 90)
public static void SaveCookie(HttpCookie cookie, int expireDays)
{
string cookieDomain = "";
string currentURL = HttpContext.Current.Request.Url.AbsoluteUri;
Regex matchNotTLD = new Regex("[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

if ((matchNotTLD.IsMatch(cookieDomain)) && (currentURL.IndexOf(cookieDomain) > -1))
{
cookie.Path = "/";
cookie.Domain = cookieDomain;
}

cookie.Expires = DateTime.Now.AddDays(expireDays);
HttpContext.Current.Response.Cookies.Add(cookie);
}
在HttpModule : IHttpModule中获取cookie
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.User.Identity.Name;
......}

在本机用visual2008调试时, HttpContext.Current.User.Identity.Name隔天都可以获取用户信息,但是发布到服务器空间时,过几十分钟后就获取不到了,必须重新登录。
...全文
309 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
myhope88 2015-04-10
  • 打赏
  • 举报
回复
参考记住密码功能就行了,就写入cookie就行了
mmm_guobatehao 2015-04-10
  • 打赏
  • 举报
回复
使用Cookie实现密码记忆功能示例 <asp:CheckBox ID="ckbauto" runat="server" Text="记住密码" />//前台设置是否记住密码 protected void Button1_Click(object sender, EventArgs e)//cs页面设置记忆功能 { if (txtname.Text.Trim().Equals("mr") && txtpwd.Text.Trim().Equals("mrsoft")) { Session["username"] = txtname.Text.Trim(); if (ckbauto.Checked) { if (Request.Cookies["username"] == null) { Response.Cookies["username"].Expires = DateTime.Now.AddDays(30); Response.Cookies["userpwd"].Expires = DateTime.Now.AddDays(30); Response.Cookies["username"].Value = txtname.Text.Trim(); Response.Cookies["userpwd"].Value = txtpwd.Text.Trim(); } }//codego.net/15/1/1/ Response.Redirect("admin.aspx"); } else { ClientScript.RegisterStartupScript(this.GetType(),"","alert('用户名或密码错误!');",true); } }
  • 打赏
  • 举报
回复
Add调用完了再调用Set,多试试呢,馊主意

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧