熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

一個簡單的ASP.NET Forms 身份認證的實例方法

2013-11-13 10:38:06  來源: .NET編程 
當訪問默認首頁defaultaspx時會自動跳轉到loginaspx頁面上請求登錄隨便輸入用戶名和密碼點擊“登錄”按鈕會回到首頁並顯示當前登錄的用戶名  

  Webconfig

復制代碼 代碼如下:
<configuration>
 <systemweb>
  <compilation debug="true"/>
  <authentication mode="Forms">
   <forms loginUrl="loginaspx" name = "ASPXFORMSAUTH" />
  </authentication>
  <authorization>
   <deny users="?"/>
  </authorization>
 </systemweb>
</configuration>

  
defaultaspx

復制代碼 代碼如下:
<HTML>
<HEAD>
<TITLE>首頁</TITLE>
<script language="VB" runat="server">
 Sub Page_Load(Sender As Object e As EventArgs)
  MessageText = StringFormat("你好{}" ContextUserIdentityName)
 End Sub
 sub btnSignout_Click(Sender as Object E as EventArgs)
  FormsAuthenticationSignOut()
  ResponseRedirect("loginaspx")
 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>

  
loginaspx

復制代碼 代碼如下:

  
<HEAD>
<TITLE>首頁</TITLE>
<script lanugage="c#" runat="server">
 private void Page_Load(object sender EventArgs e)
 {
  if (RequestIsAuthenticated)
    ResponseRedirect("defaultaspx");
 }
 void btnLogin_Click(Object sender EventArgs e)
 {
  if (txtUsernameText != null && txtUsernameText != StringEmpty && txtPasswordText != null && txtPasswordText != StringEmpty)
   FormsAuthenticationRedirectFromLoginPage(txtUsernameText true);
  else
   lblErrorText = "錯誤的用戶名/密碼";
 }
</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>


From:http://tw.wingwit.com/Article/program/net/201311/14178.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.