關於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 S
qlCommand("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