欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个简单的ASP.NET Forms 身份认证的实例方法

程序员文章站 2024-03-31 16:48:52
web.config复制代码 代码如下:  
web.config
复制代码 代码如下:

<configuration>
 <system.web>
  <compilation debug="true"/>
  <authentication mode="forms">
   <forms loginurl="login.aspx" name = ".aspxformsauth" />
  </authentication>
  <authorization>
   <deny users="?"/>
  </authorization>
 </system.web>
</configuration>

default.aspx
复制代码 代码如下:

<html>
<head>
<title>首页</title>
<script language="vb" runat="server">
 sub page_load(sender as object, e as eventargs)
  message.text = string.format("你好,{0}", context.user.identity.name)
 end sub
 sub btnsignout_click(sender as object, e as eventargs)
  formsauthentication.signout()
  response.redirect("login.aspx")
 end sub
</script>
</head>
<body>
<asp:label id="message" runat="server"/>
<br>
<form method="post" runat="server">
 <asp:button id="btnsignout" text="退出登录" runat="server" onclick="btnsignout_click"/>
</form>
</body>
</html>

login.aspx
复制代码 代码如下:

<head>
<title>首页</title>
<script lanugage="c#" runat="server">
 private void page_load(object sender, eventargs e)
 {
  if (request.isauthenticated)
    response.redirect("default.aspx");
 }
 void btnlogin_click(object sender, eventargs e)
 {
  if (txtusername.text != null && txtusername.text != string.empty && txtpassword.text != null && txtpassword.text != string.empty)
   formsauthentication.redirectfromloginpage(txtusername.text, true);
  else
   lblerror.text = "错误的用户名/密码";
 }
</script>
</head>
<body>
<form method="post" runat="server">
 <asp:label id="lblusername" runat="server" text="用户名:"/>
    
 <asp:textbox id="txtusername" runat="server"/>
 <br>
 <br>
 <asp:label id="lblpassword" runat="server" text="密 码:"/>
    
 <asp:textbox id="txtpassword" runat="server" textmode="password"/>
 <br>
 <asp:button id="btnlogin" runat="server" text="登录" onclick="btnlogin_click" />
</form>
<hr>
 <br>
 <asp:label id="lblerror" forecolor="red" runat="server"/>
</body>
</html>