做到登录时,不像在用自己的逻辑去判断用户是否登陆,就上网搜查,得知还有此方法,这个方法用起来很简单实用,第一次使用,还有很多不理解的地方,记下来方便以后查阅更改.
使用这个方法当然需要了解里面的属性和用法,网上有很多了,可以自己搜索,我就主要贴出实现代码
1.在web.config里的<system.web>节点添加
/*loginurl 登陆界面如果没有登录则跳转到次界面 *name:cookie名称,可以自己修改 *defaultUrl:默认的页面,登陆成功自动跳转到默认界面 *timeOut:cookie保留时间 */ <authentication mode="Forms"> <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" defaultUrl="Index.aspx" timeout="600" ></forms> </authentication>
//这个节点允许所有用户访问
<authorization>
<allow users="*" />
</authorization>
<!--//这个页面节点允许任何人访问-->//设置单个页面的权限
<location path="User_ForgotPass.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
2.登录界面判断登陆成功使用FormsAuthentication.RedirectFromLoginPage方法
string txtMail = Request["txt_mail"]; string Com_Pwd = Request["txt_pwd"]; DataTable msg = ComLogin(txtMail, Com_Pwd, true); if (msg.Rows.Count > 0) { Session["name"] = msg.Rows[0][4]; Session["gs"] = msg.Rows[0][0]; //选中自动登录 if (chkbox2.Checked) {
//选中自动登录则第二个参数为true,保留cookie,cookie的持续时间与web.config中的timeout时间一样 FormsAuthentication.RedirectFromLoginPage(txtMail, true); } else { FormsAuthentication.RedirectFromLoginPage(txtMail,false); } } else { Response.Write("<script>alert('请检查输入的信息')</script>"); }
还有两种方法,同样可是实现该效果
FormsAuthentication.SetAuthCookie(txtMail,false);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(720), isPersistent, userData, FormsAuthentication.FormsCookiePath); // 加密票证 string encTicket = FormsAuthentication.Encrypt(ticket); // 创建cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); HttpContext.Current.Response.Cookies.Add(cookie);