瀏覽代碼

支持验证码

懒得勤快 6 年之前
父節點
當前提交
49d78bfdc2
共有 2 個文件被更改,包括 147 次插入51 次删除
  1. 47 51
      Masuit.Tools.Core/Net/WebExtension.cs
  2. 100 0
      Masuit.Tools.Core/Strings/ValidateCode.cs

+ 47 - 51
Masuit.Tools.Core/Net/WebExtension.cs

@@ -2,7 +2,6 @@
 using Masuit.Tools.Logging;
 using Masuit.Tools.Models;
 using Masuit.Tools.NoSQL;
-using Masuit.Tools.Security;
 using Microsoft.AspNetCore.Http;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
@@ -301,12 +300,12 @@ namespace Masuit.Tools.Core.Net
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
 
-            var sessionKey = HttpContext2.Current.Request.Cookies["SessionID"];
-            if (string.IsNullOrEmpty(sessionKey))
-            {
-                sessionKey = Guid.NewGuid().ToString().AESEncrypt();
-                HttpContext2.Current.Response.Cookies.Append("SessionID", sessionKey);
-            }
+            //var sessionKey = HttpContext2.Current.Request.Cookies["SessionID"];
+            //if (string.IsNullOrEmpty(sessionKey))
+            //{
+            //    sessionKey = Guid.NewGuid().ToString().AESEncrypt();
+            //    HttpContext2.Current.Response.Cookies.Append("SessionID", sessionKey);
+            //}
 
             if (session != null)
             {
@@ -317,7 +316,7 @@ namespace Masuit.Tools.Core.Net
             {
                 using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
                 {
-                    redisHelper.SetHash("Session:" + sessionKey, key, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
+                    redisHelper.SetHash("Session:" + HttpContext2.Current.Connection.Id, key, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
                 }
             }
             catch
@@ -337,7 +336,15 @@ namespace Masuit.Tools.Core.Net
         /// <param name="session"></param>
         /// <param name="key">键</param>
         /// <returns>对象</returns>
-        public static T Get<T>(this ISession session, string key) => JsonConvert.DeserializeObject<T>(session.GetString(key));
+        public static T Get<T>(this ISession session, string key)
+        {
+            string value = session.GetString(key);
+            if (string.IsNullOrEmpty(value))
+            {
+                return default(T);
+            }
+            return JsonConvert.DeserializeObject<T>(value);
+        }
 
         /// <summary>
         /// 从Redis取Session
@@ -353,42 +360,35 @@ namespace Masuit.Tools.Core.Net
             {
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
-
-            var sessionKey = HttpContext2.Current.Request.Cookies["SessionID"];
-            if (!string.IsNullOrEmpty(sessionKey))
+            T obj = default(T);
+            if (_ != null)
             {
-                T obj = default(T);
-                if (_ != default(T))
-                {
-                    obj = _.Get<T>(key);
-                }
+                obj = _.Get<T>(key);
+            }
 
-                if (obj == default(T))
+            if (obj == default(T))
+            {
+                try
                 {
-                    try
+                    var sessionKey = "Session:" + HttpContext2.Current.Connection.Id;
+                    using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
                     {
-                        sessionKey = "Session:" + sessionKey;
-                        using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
+                        if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
                         {
-                            if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                            {
-                                redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
-                                return redisHelper.GetHash<T>(sessionKey, key);
-                            }
-
-                            return default(T);
+                            redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
+                            return redisHelper.GetHash<T>(sessionKey, key);
                         }
-                    }
-                    catch
-                    {
+
                         return default(T);
                     }
                 }
-
-                return obj;
+                catch
+                {
+                    return default(T);
+                }
             }
 
-            return default(T);
+            return obj;
         }
 
         /// <summary>
@@ -404,29 +404,25 @@ namespace Masuit.Tools.Core.Net
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
 
-            var sessionKey = HttpContext2.Current.Request.Cookies["SessionID"];
-            if (!string.IsNullOrEmpty(sessionKey))
+            if (session != null)
             {
-                if (session != null)
-                {
-                    session.Remove(key);
-                }
+                session.Remove(key);
+            }
 
-                try
+            try
+            {
+                var sessionKey = "Session:" + HttpContext2.Current.Connection.Id;
+                using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
                 {
-                    sessionKey = "Session:" + sessionKey;
-                    using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
+                    if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
                     {
-                        if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                        {
-                            redisHelper.DeleteHash(sessionKey, key);
-                        }
+                        redisHelper.DeleteHash(sessionKey, key);
                     }
                 }
-                catch (Exception e)
-                {
-                    LogManager.Error(e);
-                }
+            }
+            catch (Exception e)
+            {
+                LogManager.Error(e);
             }
         }
 

+ 100 - 0
Masuit.Tools.Core/Strings/ValidateCode.cs

@@ -0,0 +1,100 @@
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Masuit.Tools.Strings
+{
+    /// <summary>
+    /// 画验证码
+    /// </summary>
+    public static class ValidateCode
+    {
+        /// <summary>
+        /// 生成验证码
+        /// </summary>
+        /// <param name="length">指定验证码的长度</param>
+        /// <returns>验证码字符串</returns>
+        public static string CreateValidateCode(int length)
+        {
+            string ch = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ1234567890@#$%&?";
+            byte[] b = new byte[4];
+            new RNGCryptoServiceProvider().GetBytes(b);
+            Random r = new Random(BitConverter.ToInt32(b, 0));
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < length; i++)
+            {
+                sb.Append(ch[r.Next(ch.Length)]);
+            }
+
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 创建验证码的图片
+        /// </summary>
+        /// <param name="validateCode">验证码序列</param>
+        /// <param name="context">当前的HttpContext上下文对象</param>
+        /// <param name="fontSize">字体大小,默认值22px</param>
+        /// <param name="lineHeight">行高,默认36px</param>
+        /// <exception cref="Exception">The operation failed.</exception>
+        public static byte[] CreateValidateGraphic(this HttpContext context, string validateCode, int fontSize = 22, int lineHeight = 36)
+        {
+            using (Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight))
+            {
+                using (Graphics g = Graphics.FromImage(image))
+                {
+                    //生成随机生成器
+                    Random random = new Random();
+                    //清空图片背景色
+                    g.Clear(Color.White);
+                    //画图片的干扰线
+                    for (int i = 0; i < 75; 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[] fonts =
+                    {
+                        new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
+                        new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
+                        new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                        new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                        new Font("楷体", fontSize, 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, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
+
+                    //画图片的前景干扰点
+                    for (int i = 0; i < 300; 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);
+                    //保存图片数据
+                    using (MemoryStream stream = new MemoryStream())
+                    {
+                        image.Save(stream, ImageFormat.Jpeg);
+                        //输出图片流
+                        context.Response.Clear();
+                        context.Response.ContentType = "image/jpeg";
+                        return stream.ToArray();
+                    }
+                }
+            }
+        }
+    }
+}