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 }