關于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();
}
新聞熱點
疑難解答
圖片精選