login.aspx

来自「C#开发者可使用的经典案例集,源自于ASP.NET经典范例50讲」· ASPX 代码 · 共 65 行

ASPX
65
字号
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Security.Cryptography" %>

<html>
  <script language="C#" runat=server>
  private DataSet ReadAccountFile(string fileName)
  {
    DataSet dataSet = new DataSet();
    dataSet.ReadXml(fileName);
    return dataSet;
  }

  private bool Authenticate(string userName, string password)
  {
    // Verify input
    if(userName == "" || password == "")
      return false;

    //Calculate hash value of password
    UnicodeEncoding ue = new UnicodeEncoding();
    byte[] hashSource = ue.GetBytes(password);
    SHA512 shaM = new SHA512Managed();
    byte[] hashResult = shaM.ComputeHash(hashSource);
    string passwordHash = "";
    foreach(byte b in hashResult)
      passwordHash += b.ToString("X2");

    // Go throught the datatable for this account
    DataSet dataSet = ReadAccountFile(Server.MapPath("Account.xml"));
    foreach(DataRow row in dataSet.Tables[0].Rows)
    {
      if((string)row["UserName"] == userName && (string)row["Password"] == passwordHash)
        return true;
    }
    return false;
  }
  public void Login_Click(Object sender, EventArgs E)
  {
    if ( Authenticate(txtUserName.Text, txtPassword.Text))
    {
      FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
    }
    else 
    {
      Msg.Text += "Invalid User name or password: Please try again.";
    }
  }
  </script>
  <body>
  <form runat="server">
    <h3>登录页面</h3>
    <table><tr>
        <td>用户名:</td>
        <td><asp:TextBox id="txtUserName" runat="server"/></td>
      </tr><tr>
        <td>密码:</td>
        <td><asp:TextBox id="txtPassword" TextMode="password" runat="server"/></td>
    </tr></table>
    <asp:Button runat="server" OnClick="Login_Click" Text="登录"/> 
    <asp:Label id="Msg" ForeColor="red" runat="server" />
  </form>
</body>
</html>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?