ASP.NET—From验证:全部代码及讲解
2008-02-22 09:40:41来源:互联网 阅读 ()
关于Forms验证的文章网上千百篇,但我花了1天半的时间学会了“一点点”,
现在把代码分享出来,希望对像我一样的初学者所有帮助,也希望高手给指点一下:
--------------------------------------------------------------------------------
Step 1:新建数据库(库:MyForms ;表:users ;字段:ID,userName, userPwd);
Step 2:新建网站,web.config 的文件全部代码如下:
web.config 的全部代码
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true"/>
<sessionState cookieless="AutoDetect"/>
<!--解决当浏览器端禁用Cookie时-->
<authentication mode="Forms">
<forms name="CookieName" loginUrl="login.aspx" protection="All"></forms>
<!--loginUrl为登录面URL,如果没有身份验证Cookie,客户端将被重定向到此URL-->
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
</configuration>
Step 3:添加一个 login.aspx 页面;拖2个 TextBox ,1个Button 和1个CheckBox ;
并将CheckBox 的text 属性设为:“是否保存Cookis ";
Step 4:login.aspx 的隐藏代码如下:
login 全部隐藏代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient; //导入命名空间
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userName = TextBox1.Text.Trim();
string userPwd = TextBox2.Text.Trim();
SqlConnection con = new SqlConnection("Server=.;Database=MyForms;User ID=sa;Password=123456");
con.Open();
SqlCommand cmd = new SqlCommand("select count(*) from users where userName='" userName "' and userPwd='" userPwd "'", con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
System.Web.Security.FormsAuthentication.SetAuthCookie(this.TextBox1.Text, this.CheckBox1.Checked);
Response.Redirect("Default.aspx");
//上面两行,也可以换成下面一行,如通过验证则直接转向请求的页面,而不需要Responsel.Redirect("");
//System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.TextBox1.Text, false);
}
else
{
Response.Write("用户不合法");
}
}
}
Step 5:拖一个Button 到 Default.aspx 上,将其text 属性设为"登出",其事件代码如下:
Button 事件代码
protected void Button1_Click(object sender, EventArgs e)
{
System.Web.Security.FormsAuthentication.SignOut();
}
http://www.cnblogs.com/yoyebina/archive/2006/12/03/580121.html
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash