以下代码如果有不对或者不妥之处,还望大神们指点一二
或者有同学者有问题或建议,一定要提出来,共同探讨
小弟在此感谢!
前台代码:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <div align="center"> <h1>用户登录页面</h1> <form id="form1" runat="server"> <p> <asp:Label ID="lbusername" runat="server">学号:</asp:Label> <asp:TextBox ID="txtNum" runat="server"></asp:TextBox> </p> <p> <asp:Label ID="lbpsw" runat="server">密 码:</asp:Label> <asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox> </p> <p> <asp:Label ID="lblyzm" runat="server">验证码:</asp:Label> <asp:TextBox ID="txtYZM" runat="server" ></asp:TextBox> <label id="lblcode" runat="server"><asp:ImageButton ID="ImageButton1" runat="server" Height="25px" Width="54px" /></label> </p> <p> <asp:Label ID="lblText" runat="server" Text=""></asp:Label></p> <p><asp:Button ID="btnLogin" runat="server" Text="登录" onclick="btnLogin_Click" /> </p> </form> </div> </body>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Drawing; using System.Text; using System.Security.Cryptography; namespace ado.netDemo1 { public partial class Login : System.Web.UI.Page { SqlConnection connStr = new SqlConnection( ConfigurationManager.ConnectionStrings["connStr"].ToString()); string sql; protected void Page_Load(object sender, EventArgs e) { ImageButton1.ImageUrl = "~/picture.aspx"; } protected void btnLogin_Click(object sender, EventArgs e) { if (lblyzm.Text.Trim() == null) { lblText.ForeColor = Color.Red; lblText.Text = "请输入验证码!"; } else if (txtYZM.Text.Trim() != Session["CheckCode"].ToString()) { lblText.ForeColor = Color.Red; lblText.Text = "验证码错误,请重新填写!"; } else { if ((txtNum.Text.Trim() == "") && (txtpwd.Text.Trim() == "")) { lblText.ForeColor = Color.Red; lblText.Text = "请您输入用户名和密码!"; } else if ((txtNum.Text.Trim() == "") || (txtpwd.Text.Trim() == "")) { lblText.ForeColor = Color.Red; lblText.Text = "用户名或密码不正确!"; } else { string hashedPWD = Encrypt(txtpwd.Text.Trim()); sql = "select * from tb_Students where SID='" + txtNum.Text.Trim() + "'and password='" +hashedPWD + "'"; connStr.Open(); SqlCommand cmd = new SqlCommand(sql, connStr); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Session["Username"] = dr.GetValue(dr.GetOrdinal("name")); Response.Write(@"<script>window.alert('登录成功');window.location ='Test1.aspx'</script>"); } } } connStr.Close(); } public static string Encrypt(string cleanString) { Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes); return BitConverter.ToString(hashedBytes); } } }
运行截图: