关于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();
}
新闻热点
疑难解答
图片精选