一.登录界面
建立登录文件夹Login,在此目录下面建立如下文件:
Index.htm:登录页面
ValidateCode.cs:生成验证码
ProcessVerification.ashx:处理验证码
CommonHelper.cs:帮助处理类
Login.ashx:处理登录
Index.htm:登录页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>XX后台管理系统登录</title> <link href="../css/StyleHouTai.css" rel="stylesheet" /> <script type="text/javascript"> if (window.parent.window != window) { window.top.location.href = "/Home/CheckLogin"; } </script> <script src="../script/jquery-1.8.3.js" type="text/javascript"></script> <script src="../script/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> <script type="text/javascript"> function changeCheckCode() { $("#img").attr("src",$("#img").attr("src")+1); } function afterLogin(data) { var serverData = data.split(':'); if (serverData[0] == "ok") { window.location.href = "/Home/Index"; } else if (serverData[0] == "no") { $("#errorMsg").text(serverData[1]); changeCheckCode(); } else { $("#errorMsg").text("系统繁忙"); } } function blurCode(id,idErr,errCode) { $(id).blur(function () { var loginCode = $(id).val(); //因js不支持trim()函数,需要使用此函数时添加以下语句 //String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); } //if (loginCode.trim().length <= 0) { if ($.trim(loginCode).length <= 0) { $(idErr).text(errCode); return; } else { $(idErr).text(""); } }); } $(function () { blurCode('#LoginCode', '#LoginCodeErr', '请输入账号'); blurCode('#LoginPwd', '#LoginPwdErr', '请输入密码'); blurCode('#code', '#codeErr', '请输入验证码'); }); // $('#btnLogin').click(function () { // var loginCode = $("#LoginCode").val(); // var loginPwd = $("#LoginPwd").val(); // if (loginCode.length <= 0) { // alert("请输入账号"); // } // $("#errorMsg").text("登录失败"); // changeCheckCode(); // }); /* $(function () { $('#LoginCode').blur(function () { var loginCode = $("#LoginCode").val(); if (loginCode.trim().length <= 0) { $("#LoginCodeErr").text("请输入账号"); } else { $("#LoginCodeErr").text(""); } }); $('#LoginPwd').blur(function () { var loginPwd = $("#LoginPwd").val(); if (loginPwd.trim().length <= 0) { $("#LoginPwdErr").text("请输入密码"); } else { $("#LoginPwdErr").text(""); } }); $('#code').blur(function () { var code = $("#code").val(); if (code.trim().length <= 0) { $("#codeErr").text("请输入验证码"); } else { $("#codeErr").text(""); } }); });*/ </script> </head> <body style="padding: 10px"> <div id="login"> <div id="loginlogo"> </div> <div id="loginpanel"> <div class="panel-h"> </div> <div class="panel-c"> <div class="panel-c-l"> <form action="Login.ashx" method="post"> <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td align="left" colspan="2"> <h3>请使用XX系统账号登录</h3> </td> </tr> <tr> <td align="right">账号:</td> <td align="left"> <input type="text" style="width:150px" name="LoginCode" id="LoginCode" class="login-text" /> <span id="LoginCodeErr" style="color:Red"></span> </td> </tr> <tr> <td align="right"> 密码: </td> <td align="left"> <input type="password" style="width:150px" name="LoginPwd" id="LoginPwd" value="" class="login-text" /> <span id="LoginPwdErr" style="color:Red"></span> </td> </tr> <tr> <td> 验证码: </td> <td align="left"> <input type="text" style="width:150px" class="login-text" id="code" name="vCode" value="" /> <span id="codeErr" style="color:Red"></span> </td> </tr> <tr> <td> </td> <td> <img id="img" src="ProcessVerification.ashx?id=1" style="float: left; height: 24px;" /> <div style="float: left; margin-left: 5px; margin-top: 10px;"> <a href="javascript:void(0)" onclick="changeCheckCode();return false;">看不清,换一张</a> </div> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" name="btnLogin" id="btnLogin" value="登录" class="login-btn" /> <span id="errorMsg"></span> </td> </tr> </tbody> </table> </form> </div> <div class="panel-c-r"> <p> 请从左侧输入登录账号和密码登录</p> <p> 如果遇到系统问题,请联系网络管理员。</p> <p> 如果没有账号,请联系网站管理员。 </p> <p> ......</p> </div> </div> <div class="panel-f"> </div> </div> <div id="logincopyright"> Copyright 2015 www.syfpc.com </div> </div> </body> </html>
ValidateCode.cs:生成验证码
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace modelInput { public class ValidateCode { public ValidateCode() { } /// <summary> /// 验证码的最大长度 /// </summary> public int MaxLength { get { return 10; } } /// <summary> /// 验证码的最小长度 /// </summary> public int MinLength { get { return 1; } } /// <summary> /// 生成验证码 /// </summary> /// <param name="length">指定验证码的长度</param> /// <returns></returns> public string CreateValidateCode(int length) { int[] randMembers = new int[length]; int[] validateNums = new int[length]; string validateNumberStr = ""; //生成起始序列值 int seekSeek = unchecked((int)DateTime.Now.Ticks); Random seekRand = new Random(seekSeek); int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginSeek += 10000; seeks[i] = beginSeek; } //生成随机数字 for (int i = 0; i < length; i++) { Random rand = new Random(seeks[i]); int pownum = 1 * (int)Math.Pow(10, length); randMembers[i] = rand.Next(pownum, Int32.MaxValue); } //抽取随机数字 for (int i = 0; i < length; i++) { string numStr = randMembers[i].ToString(); int numLength = numStr.Length; Random rand = new Random(); int numPosition = rand.Next(0, numLength - 1); validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); } //生成验证码 for (int i = 0; i < length; i++) { validateNumberStr += validateNums[i].ToString(); } return validateNumberStr; } /// <summary> /// 创建验证码的图片 /// </summary> /// <param name="context">要输出到的page对象</param> /// <param name="validateNum">验证码</param> public void CreateValidateGraphic(string validateCode, HttpContext context) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的干扰线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2); //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); image.Dispose(); } } /// <summary> /// 得到验证码图片的长度 /// </summary> /// <param name="validateNumLength">验证码的长度</param> /// <returns></returns> public static int GetImageWidth(int validateNumLength) { return (int)(validateNumLength * 12.0); } /// <summary> /// 得到验证码的高度 /// </summary> /// <returns></returns> public static double GetImageHeight() { return 22.5; } //C# MVC 升级版 /// <summary> /// 创建验证码的图片 /// </summary> /// <param name="containsPage">要输出到的page对象</param> /// <param name="validateNum">验证码</param> public byte[] CreateValidateGraphic(string validateCode) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的干扰线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2); //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 return stream.ToArray(); } finally { g.Dispose(); image.Dispose(); } } } }
ProcessVerification.ashx:处理验证码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using modelInput; using System.Drawing; using System.Drawing.Imaging; namespace XX管理系统.Login { /// <summary> /// ProcessVerification 的摘要说明 /// </summary> public class ProcessVerification : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; ValidateCode validateCode = new ValidateCode(); string code = validateCode.CreateValidateCode(4); //创建cookie对象 HttpCookie cookie = new HttpCookie("vCode"); //将cookie值等于自动生成的验证码 cookie.Value = code; //更新cookie值 context.Response.SetCookie(cookie); using (Bitmap bmp = new Bitmap(100, 50))//创建一个尺寸为500*500的内存图片 using (Graphics g = Graphics.FromImage(bmp))//得到图片的画布 { g.DrawString(code, new Font(FontFamily.GenericSerif, 30), Brushes.Red, 0, 0);//Font应该被释放 bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);//图片保存到输出流 } } public bool IsReusable { get { return false; } } } }
CommonHelper.cs:帮助处理类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace XX管理系统 { public class CommonHelper { /// <summary> /// 返回HTML文件内容 /// </summary> /// <param name="fileName">HTML文件</param> /// <returns></returns> public static string ReadHtml(string fileName) { HttpContext context = HttpContext.Current; string fullpath = context.Server.MapPath(fileName); string html = File.ReadAllText(fullpath); return html; } } }
Login.ashx:处理登录
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //LoginCode,LoginPwd, string loginCode = context.Request["LoginCode"];//用户名 string loginPwd = context.Request["LoginPwd"];//密码 string vCode = context.Request["vCode"];//验证码 //获取客户端的cookie值 HttpCookie cookie = context.Request.Cookies["vCode"]; if (cookie == null) { context.Response.Write("找不到系统生成的验证码"); context.Response.Redirect("Index.htm"); return; } if (vCode != cookie.Value) { context.Response.Write("验证码错误"); context.Response.Redirect("Index.htm"); return; } int r = (int)SQLHelper.ExecuteScalar("select count(*) from Users where name=@loginCode and password=@loginPwd", new SqlParameter { ParameterName = "@loginCode", Value = loginCode }, new SqlParameter { ParameterName = "@loginPwd",Value=loginPwd }); if (r == 1) { context.Response.Redirect("../Home.htm"); } }