Common层添加用于生产验证码的类:ValidateCode.cs
验证码:
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Drawing.Drawing2D; 5 using System.Drawing.Imaging; 6 using System.IO; 7 using System.Linq; 8 using System.Text; 9 using System.Threading.Tasks; 10 using System.Web; 11 12 namespace Reservation.Common 13 { 14 public class ValidateCode 15 { 16 public ValidateCode() 17 { 18 } 19 /// <summary> 20 /// 验证码的最大长度 21 /// </summary> 22 public int MaxLength 23 { 24 get { return 10; } 25 } 26 /// <summary> 27 /// 验证码的最小长度 28 /// </summary> 29 public int MinLength 30 { 31 get { return 1; } 32 } 33 /// <summary> 34 /// 生成验证码 35 /// </summary> 36 /// <param name="length">指定验证码的长度</param> 37 /// <returns></returns> 38 public string CreateValidateCode(int length) 39 { 40 int[] randMembers = new int[length]; 41 int[] validateNums = new int[length]; 42 string validateNumberStr = ""; 43 //生成起始序列值 44 int seekSeek = unchecked((int)DateTime.Now.Ticks); 45 Random seekRand = new Random(seekSeek); 46 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); 47 int[] seeks = new int[length]; 48 for (int i = 0; i < length; i++) 49 { 50 beginSeek += 10000; 51 seeks[i] = beginSeek; 52 } 53 //生成随机数字 54 for (int i = 0; i < length; i++) 55 { 56 Random rand = new Random(seeks[i]); 57 int pownum = 1 * (int)Math.Pow(10, length); 58 randMembers[i] = rand.Next(pownum, Int32.MaxValue); 59 } 60 //抽取随机数字 61 for (int i = 0; i < length; i++) 62 { 63 string numStr = randMembers[i].ToString(); 64 int numLength = numStr.Length; 65 Random rand = new Random(); 66 int numPosition = rand.Next(0, numLength - 1); 67 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); 68 } 69 //生成验证码 70 for (int i = 0; i < length; i++) 71 { 72 validateNumberStr += validateNums[i].ToString(); 73 } 74 return validateNumberStr; 75 } 76 /// <summary> 77 /// 创建验证码的图片 78 /// </summary> 79 /// <param name="context">要输出到的page对象</param> 80 /// <param name="validateNum">验证码</param> 81 public void CreateValidateGraphic(string validateCode, HttpContext context) 82 { 83 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 84 Graphics g = Graphics.FromImage(image); 85 try 86 { 87 //生成随机生成器 88 Random random = new Random(); 89 //清空图片背景色 90 g.Clear(Color.White); 91 //画图片的干扰线 92 for (int i = 0; i < 25; i++) 93 { 94 int x1 = random.Next(image.Width); 95 int x2 = random.Next(image.Width); 96 int y1 = random.Next(image.Height); 97 int y2 = random.Next(image.Height); 98 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 99 } 100 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 101 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 102 Color.Blue, Color.DarkRed, 1.2f, true); 103 g.DrawString(validateCode, font, brush, 3, 2); 104 //画图片的前景干扰点 105 for (int i = 0; i < 100; i++) 106 { 107 int x = random.Next(image.Width); 108 int y = random.Next(image.Height); 109 image.SetPixel(x, y, Color.FromArgb(random.Next())); 110 } 111 //画图片的边框线 112 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 113 //保存图片数据 114 MemoryStream stream = new MemoryStream(); 115 image.Save(stream, ImageFormat.Jpeg); 116 //输出图片流 117 context.Response.Clear(); 118 context.Response.ContentType = "image/jpeg"; 119 context.Response.BinaryWrite(stream.ToArray()); 120 } 121 finally 122 { 123 g.Dispose(); 124 image.Dispose(); 125 } 126 } 127 /// <summary> 128 /// 得到验证码图片的长度 129 /// </summary> 130 /// <param name="validateNumLength">验证码的长度</param> 131 /// <returns></returns> 132 public static int GetImageWidth(int validateNumLength) 133 { 134 return (int)(validateNumLength * 12.0); 135 } 136 /// <summary> 137 /// 得到验证码的高度 138 /// </summary> 139 /// <returns></returns> 140 public static double GetImageHeight() 141 { 142 return 22.5; 143 } 144 145 146 147 //C# MVC 升级版 148 /// <summary> 149 /// 创建验证码的图片 150 /// </summary> 151 /// <param name="containsPage">要输出到的page对象</param> 152 /// <param name="validateNum">验证码</param> 153 public byte[] CreateValidateGraphic(string validateCode) 154 { 155 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 156 Graphics g = Graphics.FromImage(image); 157 try 158 { 159 //生成随机生成器 160 Random random = new Random(); 161 //清空图片背景色 162 g.Clear(Color.White); 163 //画图片的干扰线 164 for (int i = 0; i < 25; i++) 165 { 166 int x1 = random.Next(image.Width); 167 int x2 = random.Next(image.Width); 168 int y1 = random.Next(image.Height); 169 int y2 = random.Next(image.Height); 170 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 171 } 172 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 173 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 174 Color.Blue, Color.DarkRed, 1.2f, true); 175 g.DrawString(validateCode, font, brush, 3, 2); 176 //画图片的前景干扰点 177 for (int i = 0; i < 100; i++) 178 { 179 int x = random.Next(image.Width); 180 int y = random.Next(image.Height); 181 image.SetPixel(x, y, Color.FromArgb(random.Next())); 182 } 183 //画图片的边框线 184 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 185 //保存图片数据 186 MemoryStream stream = new MemoryStream(); 187 image.Save(stream, ImageFormat.Jpeg); 188 //输出图片流 189 return stream.ToArray(); 190 } 191 finally 192 { 193 g.Dispose(); 194 image.Dispose(); 195 } 196 } 197 } 198 }
新建控制器:LoginController,用于控制 登录相关功能的页面
ValidateCode()方法用于生产验证码。
1 /// <summary> 2 /// 生产验证码 3 /// </summary> 4 /// <returns></returns> 5 public ActionResult ValidateCode() 6 { 7 ValidateCode validateCode = new ValidateCode(); 8 string code = validateCode.CreateValidateCode(4);//生成验证码 9 Session["validateCode"] = code;//存储于Session中 10 byte[] buffer = validateCode.CreateValidateGraphic(code);//创建验证码的图片 11 return File(buffer, "image/jpeg"); 12 }
home,Index 生成视图。
1 /// <summary> 2 /// PC端登录页面 3 /// </summary> 4 /// <returns></returns> 5 public ActionResult Index() 6 { 7 return View(); 8 } 9 10 /// <summary> 11 /// 首页!home视图中有js代码用于判断是否是PC端,还是手机端,PAD端,然后跳转 12 /// </summary> 13 /// <returns></returns> 14 public ActionResult home() 15 { 16 return View(); 17 }
Login/home 页面:JS代码检测浏览器是PC段还是移动端
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>home</title> 11 <script type="text/javascript"> 12 //进入页面的第一件事情:检测当前的浏览器是pc端还是移动端 13 if (/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))) { 14 //window.location.href="移动端页面的地址"; 15 //是移动端设备 16 if(/Android|Windows Phone|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){ 17 //手机 18 window.location.href = "/PhoneLogin/Index"; 19 }else if(/iPad/i.test(navigator.userAgent)){ 20 //pad 21 window.location.href = "/PadLogin/Index"; 22 } 23 } else { 24 //pc端设备 /Home/Index 25 window.location.href = "/Login/Index"; 26 } 27 </script> 28 29 </head> 30 <body> 31 <div> 32 33 </div> 34 </body> 35 </html>
Login/index 页面 :PC端登录页面,验证码和登录
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>Login</title> 11 <script src="~/Scripts/jquery-1.8.2.min.js"></script> 12 <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 13 <script src="~/Scripts/jquery.validate.min.js"></script> 14 15 16 <script type="text/javascript"> 17 18 $(function () { 19 var objusername = $("#LoginCode"); 20 objusername.trigger("select"); 21 }) 22 23 function changeCheckCode() { 24 var obj = $("#img").attr("src"); 25 $("#img").attr("src", obj + 1); 26 } 27 28 function afterLogin(data) { 29 30 var serverData = data.split(':'); 31 if (serverData[0] == "ok") { 32 33 //window.location.href = "/Home/Index" 34 if (serverData[1] == "1") { 35 window.location.href = "/Home/Index" 36 } else if (serverData[1] == "2") { 37 window.location.href = "/Manage/Index" 38 } 39 40 } else if (serverData[0] == "no") { 41 $("#errorMsg").text(serverData[1]); 42 changeCheckCode(); 43 } else { 44 window.location.href = "/Error.html" 45 } 46 } 47 48 </script> 49 50 <style type="text/css"> 51 * { 52 padding: 0; 53 margin: 0; 54 } 55 56 body { 57 text-align: center; 58 background: #4974A4; 59 } 60 61 #login { 62 width: 740px; 63 margin: 0 auto; 64 font-size: 12px; 65 } 66 67 #loginlogo { 68 width: 700px; 69 height: 100px; 70 overflow: hidden; 71 background: url('/Content/Images/login/logo.png') no-repeat; 72 margin-top: 50px; 73 } 74 75 #loginpanel { 76 width: 729px; 77 position: relative; 78 height: 300px; 79 } 80 81 .panel-h { 82 width: 729px; 83 height: 20px; 84 background: url('/Content/Images/login/panel-h.gif') no-repeat; 85 position: absolute; 86 top: 0px; 87 left: 0px; 88 z-index: 3; 89 } 90 91 .panel-f { 92 width: 729px; 93 height: 13px; 94 background: url('/Content/Images/login/panel-f.gif') no-repeat; 95 position: absolute; 96 bottom: 0px; 97 left: 0px; 98 z-index: 3; 99 } 100 101 .panel-c { 102 z-index: 2; 103 background: url('/Content/Images/login/panel-c.gif') repeat-y; 104 width: 729px; 105 height: 300px; 106 } 107 108 .panel-c-l { 109 position: absolute; 110 left: 60px; 111 top: 40px; 112 } 113 114 .panel-c-r { 115 position: absolute; 116 right: 20px; 117 top: 50px; 118 width: 222px; 119 height:150px; 120 line-height: 200%; 121 text-align: left; 122 123 /*background-color:aqua;*/ 124 } 125 126 .panel-c-l h3 { 127 color: #556A85; 128 margin-bottom: 10px; 129 } 130 131 .panel-c-l td { 132 padding: 7px; 133 } 134 135 .login-text { 136 height: 24px; 137 left: 24px; 138 border: 1px solid #e9e9e9; 139 background: #f9f9f9; 140 } 141 142 .login-text-focus { 143 border: 1px solid #E6BF73; 144 } 145 146 .login-btn { 147 width: 114px; 148 height: 29px; 149 color: #E9FFFF; 150 line-height: 29px; 151 background: url('/Content/Images/login/login-btn.gif') no-repeat; 152 border: none; 153 overflow: hidden; 154 cursor: pointer; 155 } 156 157 #txtUsername, #code, #txtPassword { 158 width: 191px; 159 } 160 161 #logincopyright { 162 text-align: center; 163 color: White; 164 margin-top: 50px; 165 } 166 167 a { 168 color: Black; 169 } 170 171 a:hover { 172 color: Red; 173 text-decoration: underline; 174 } 175 </style> 176 177 </head> 178 <body style="padding: 10px"> 179 <div id="login"> 180 <div id="loginlogo"> 181 </div> 182 <div id="loginpanel"> 183 <div class="panel-h"> 184 </div> 185 <div class="panel-c"> 186 <div class="panel-c-l"> 187 188 @using (Ajax.BeginForm("UserLogin", new { }, new AjaxOptions { OnSuccess = "afterLogin" }, new { id = "loginform" })) 189 { 190 <table cellpadding="0" cellspacing="0"> 191 <tbody> 192 <tr> 193 <td align="left" colspan="2"> 194 <h3> 195 鲜活会议访客登录系统 196 </h3> 197 </td> 198 </tr> 199 <tr> 200 <td align="right"> 201 账号: 202 </td> 203 <td align="left"> 204 <input type="text" name="LoginCode" id="LoginCode" class="login-text" /> 205 206 </td> 207 </tr> 208 <tr> 209 <td align="right"> 210 密码: 211 </td> 212 <td align="left"> 213 <input type="password" name="LoginPwd" id="LoginPwd" class="login-text" /> 214 </td> 215 </tr> 216 <tr> 217 <td> 218 验证码: 219 </td> 220 <td align="left"> 221 <input type="text" class="login-text" id="code" name="vCode" /> 222 </td> 223 </tr> 224 <tr> 225 <td></td> 226 <td> 227 <img id="img" src="/Login/ValidateCode/?id=1" style="float: left; height: 24px;" /> 228 <div style="float: left; margin-left: 5px; margin-top: 10px;"> 229 <a href="javascript:void(0)" onclick="changeCheckCode();return false;">看不清,换一张</a> 230 </div> 231 </td> 232 </tr> 233 <tr> 234 <td align="center" colspan="2"> 235 <input type="submit" id="btnLogin" value="登录" class="login-btn" /> 236 <span id="errorMsg"></span> 237 </td> 238 </tr> 239 </tbody> 240 </table> 241 } 242 </div> 243 <div class="panel-c-r" > 244 <img src="~/Content/Images/2.png" width="180px" height="180px" /> 245 </div> 246 </div> 247 <div class="panel-f"> 248 </div> 249 </div> 250 <div id="logincopyright"> 251 Copyright 2017 www.myfreshjuice.com 252 </div> 253 </div> 254 </body> 255 </html>
控制器:UserLogin()方法用于验证用户登录----调用了BLL层的GetUserInfo(),Dal层的GetUserInfo()
1 public ActionResult UserLogin() 2 { 3 //判断Session中的验证码是否为空 4 string validateconde = Session["validateCode"].ToString() == null ? string.Empty : Session["validateCode"].ToString(); 5 if (string.IsNullOrEmpty(validateconde)) 6 { 7 return Content("no:验证码错误!"); 8 } 9 Session["validateCode"] = null; 10 //判断验证码是否正确 11 string vcode = Request["vCode"].ToString(); 12 if (!vcode.Equals(validateconde, StringComparison.InvariantCultureIgnoreCase)) 13 { 14 //StringComparison.InvariantCultureIgnoreCase 使用区域敏感排序规则、固定区域来比较字符串,同时忽略被比较字符串的大小写 15 return Content("no:验证码错误!"); 16 } 17 //判断用户名和密码 18 string username = Request["LoginCode"]; 19 string userpwd = Request["LoginPwd"]; 20 UserInfoService UserInfoService = new UserInfoService(); 21 T_UserInfo UserInfo = UserInfoService.GetUserInfo(username, userpwd); 22 if (UserInfo != null) 23 { 24 Session["UserInfo"] = UserInfo;//UserInfo对象赋值给Session, 25 //调用((T_UserInfo)Session["UserInfo"]).UserName; 26 27 if(UserInfo.User_Power == "1") 28 { 29 //用户权限 30 return Content("ok:1"); 31 } 32 else if(UserInfo.User_Power =="2") 33 { 34 //管理员权限 35 return Content("ok:2"); 36 } 37 else 38 { 39 return Content("no:系统异常"); 40 } 41 42 //return Content("ok:登录成功!!"); 43 } 44 else 45 { 46 return Content("no:用户名密码错误"); 47 } 48 }
BLL :UserInfoService.cs --> GetUserInfo()
1 /// <summary> 2 /// 根据用户名和密码,返回用户信息 3 /// </summary> 4 /// <param name="username"></param> 5 /// <param name="userpassword"></param> 6 /// <returns></returns> 7 public T_UserInfo GetUserInfo(string username,string userpassword) 8 { 9 return userInfoDal.GetUserInfo(username, userpassword); 10 }
DAL:UserInfoDal.cs --> GetUserInfo()
1 /// <summary> 2 /// 验证用户,返回用户信息 3 /// </summary> 4 /// <param name="username"></param> 5 /// <param name="userpassword"></param> 6 /// <returns></returns> 7 public T_UserInfo GetUserInfo(string username,string userpassword) 8 { 9 string sql=" select * from T_userInfo where userName=@userName and userPassword=@userPassword "; 10 SqlParameter[] pars ={ 11 new SqlParameter("@userName",SqlDbType.NVarChar,50), 12 new SqlParameter("@userPassword",SqlDbType.NVarChar,50) 13 }; 14 pars[0].Value = username; 15 pars[1].Value = userpassword; 16 17 DataTable dt = SqlHelper.SelectSqlReturnDataTable(sql, CommandType.Text, pars); 18 T_UserInfo userInfo = null; 19 if(dt.Rows.Count > 0) 20 { 21 userInfo = new T_UserInfo(); 22 LoadEntity(dt.Rows[0], userInfo); 23 } 24 return userInfo; 25 } 26 27 public void LoadEntity(DataRow row, T_UserInfo userInfo) 28 { 29 userInfo.Id = Convert.ToInt32(row["id"].ToString()); 30 userInfo.UserName = row["userName"] != DBNull.Value ? row["userName"].ToString() : string.Empty; 31 userInfo.UserPassword = row["userPassword"] != DBNull.Value ? row["userPassword"].ToString() : string.Empty; 32 userInfo.UserEmail = row["userEmail"] != DBNull.Value ? row["userEmail"].ToString() : string.Empty; 33 userInfo.User_BM = row["user_BM"] != DBNull.Value ? row["user_BM"].ToString() : string.Empty; 34 userInfo.Add_time = Convert.ToDateTime(row["add_time"]); 35 userInfo.User_FullName = row["user_FullName"] != DBNull.Value ? row["user_FullName"].ToString() : string.Empty; 36 userInfo.User_Power = row["user_Power"] != DBNull.Value ? row["user_Power"].ToString() : string.Empty; 37 }