asp.net
關於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();
}