1.在公共类ImageHelper中编写公共方法,产生随机验证码
/// <summary> /// 产生随机验证码 /// </summary> /// <returns></returns> public string GetString() { string randString = ""; Random random = new Random(); do { //使用DateTime.Now.Millisecond作为生成随机数的参数,增加随机性 randString += RandCharString.Substring(random.Next(DateTime.Now.Millisecond) % RandCharString.Length, 1); } while (randString.Length < 4); return randString; }
/// <summary> /// 获得图片 /// </summary> /// <param name="checkCode"></param> /// <returns></returns> public Image GetImage(string checkCode) public Image GetImage(string checkCode) { //颜色列表,用于验证码、噪线、噪点 Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; //字体列表,用于验证码 string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" }; Random rnd = new Random(); Bitmap bmp = new Bitmap(100, 40); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); //画噪线 for (int i = 0; i < 10; i++) { int x1 = rnd.Next(100); int y1 = rnd.Next(40); int x2 = rnd.Next(100); int y2 = rnd.Next(40); Color clr = color[rnd.Next(color.Length)]; g.DrawLine(new Pen(clr), x1, y1, x2, y2); } //画验证码字符串 for (int i = 0; i < checkCode.Length; i++) { string fnt = font[rnd.Next(font.Length)]; Font ft = new Font(fnt, 18); Color clr = color[rnd.Next(color.Length)]; g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8); } //画噪点 for (int i = 0; i < 100; i++) { int x = rnd.Next(bmp.Width); int y = rnd.Next(bmp.Height); Color clr = color[rnd.Next(color.Length)]; bmp.SetPixel(x, y, clr); } g.Dispose(); return bmp; }
2.新建一个页面,前台不要添加代码,在cs中添加一下函数
protected void Page_Load(object sender, EventArgs e)
{
ImageHelper.ImageHelper randImage = new ImageHelper.ImageHelper();//调用公共类方法 string checkCode = randImage.GetString();//获取随机串 System.Drawing.Image bmp = randImage.GetImage(checkCode); HttpCookie cookie = new HttpCookie("CheckCode",checkCode);//新建Cookie值 Response.AppendCookie(cookie); //清除该页输出缓存,设置该页无缓存 Response.Buffer = true; Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); Response.Expires = 0; Response.CacheControl = "no-cache"; Response.AppendHeader("Pragma", "No-Cache"); //将验证码图片写入内存流,并将其以 "image/Png" 格式输出 MemoryStream ms = new MemoryStream(); try { bmp.Save(ms, ImageFormat.Png); Response.ClearContent(); Response.ContentType = "image/Png"; Response.BinaryWrite(ms.ToArray()); } finally { //显式释放资源 bmp.Dispose(); }
}
3.登录页面前台
<table width="40%"> <tr> <td> <asp:Label runat="server" Text="用户名"></asp:Label> </td> <td> <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="txtUserName" CssClass="red" ErrorMessage="必须填写“用户名”。"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label runat="server" Text="密码"></asp:Label> </td> <td> <asp:TextBox runat="server" ID="txtPassword" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtPassword" CssClass="red" ErrorMessage="必须填写“密码”" ></asp:RequiredFieldValidator> </td> </tr> </table> <table width="50%"> <tr> <td> <asp:TextBox ID="txtCheckCode" runat="server" Width="70"> </asp:TextBox> <asp:Image ID="img" runat="server" /> <a href="javascript:change()">看不清?换一张</a> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtCheckCode" CssClass="red" ErrorMessage="校验码必填"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Button ID="btnLogin" runat="server" Text="登录" onclick="btnLogin_Click" /> </td> </tr> </table>
其中,“看不清?换一张”连接的点击事件函数
<script type="text/javascript">
function change() {
document.getElementById('<%=img.ClientID %>').src = document.getElementById('<%=img.ClientID %>').src + '?';
}
</script>
这里,使用'<%=img.ClientID %>'获取Image控件的ID值,是因为使用了母板页,导致获取的ID将不是原先定义的“img”,而是“Maincontent_img”,
运行程序,在图片上右击-查看元素可发现
如果document.getElementById('img').src就获取不到Image的地址了
4.登录页面后台
protected void Page_Load(object sender, EventArgs e) { img.ImageUrl = "Check.aspx"; } protected void btnLogin_Click(object sender, EventArgs e) { string str = Request.Cookies["CheckCode"].Value.ToString();//获取Cookies值 if (txtCheckCode.Text.Trim().Equals(str)) { bool isok = Membership.ValidateUser(txtUserName.Text.Trim(), txtPassword.Text.Trim());//验证登录用户名、密码 if (isok) { FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), false);//验证通过,登录账户 Response.Redirect("Default.aspx"); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "err", "alert('登录失败');", true); } } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "err", "alert('验证码输入错误');", true); } }
到此,就能够通过Membership实现带有验证码的登录了