标签:
要做一个防止一个Ip攻击网站的功能,想到了使用Cache,里面有Add 和 Insert方法。方法中有很多参数,他是以key-Value 方式存储,区别在于,Add方法一旦创建,里面的数据不可以修改。Inset 可以key不变修改 value参数。
设计思路是这样的,key为ip,value 为次数。代码如下:
1 /// <summary> 2 /// 获取当前应用程序指定CacheKey的Cache值 3 /// </summary> 4 /// <param name="CacheKey"></param> 5 /// <returns></returns> 6 public static object GetCache(string CacheKey) 7 { 8 System.Web.Caching.Cache objCache = HttpRuntime.Cache; 9 return objCache[CacheKey]; 10 } 11 12 /// <summary> 13 /// 设置当前应用程序指定CacheKey的Cache值 14 /// </summary> 15 /// <param name="CacheKey"></param> 16 /// <param name="objObject"></param> 17 /// <param name="m">分钟</param> 18 public static void SetCache(string CacheKey, object objObject, int m) 19 { 20 System.Web.Caching.Cache objCache = HttpRuntime.Cache; 21 objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddMinutes(m), Cache.NoSlidingExpiration); 22 } 23 /// <summary> 24 /// 25 /// </summary> 26 /// <param name="ip"></param> 27 /// <param name="duration">时常(分钟)</param> 28 /// <param name="count"> 访问量最大阀门值</param> 29 /// <returns></returns> 30 public static bool IpConfig(string ip, int duration = 1, int count = 10) 31 { 32 bool result = false; 33 string urlIndex = "~/css/IpConfig.xml"; 34 string FileName = System.Web.HttpContext.Current.Server.MapPath(urlIndex); 35 XDocument doc = XDocument.Load(FileName); 36 37 var rel = from p in doc.Descendants("item") where p.Attribute("ip").Value.ToLower() == ip select p; 38 result = (rel != null && rel.Count() > 0) ? true : false; 39 if (!result) 40 { 41 object obj = null; 42 if (string.IsNullOrWhiteSpace(ip)) { result = true; } 43 else 44 { 45 obj = GetCache(ip); 46 if (obj != null) 47 { 48 int _count = (int)obj; 49 if (_count >= count) 50 { 51 if (_count == count) 52 { 53 insertIP(ip); 54 sendmobile(ip); 55 } 56 return true; 57 } 58 else 59 { 60 System.Web.Caching.Cache objCache = HttpRuntime.Cache; 61 objCache.Insert(ip, _count + 1, null, DateTime.Now.AddSeconds(duration), Cache.NoSlidingExpiration); 62 } 63 } 64 else 65 { 66 SetCache(ip, 1, duration); 67 } 68 } 69 } 70 return result; 71 } 72 73 74 #region 将IP插入到XML中 75 public static void insertIP(string ip) 76 { 77 string urlIndex = "~/css/IpConfig.xml"; 78 string FileName = System.Web.HttpContext.Current.Server.MapPath(urlIndex); 79 XmlDocument xmlDoc = new XmlDocument(); 80 xmlDoc.Load(FileName); 81 XmlNode root = xmlDoc.SelectSingleNode("root"); 82 XmlNode root0 = root.ChildNodes.Item(0); 83 XmlElement xe1 = xmlDoc.CreateElement("item"); 84 xe1.SetAttribute("ip", ip); 85 86 root0.AppendChild(xe1); 87 xmlDoc.Save(FileName); 88 } 89 #endregion 90 91
标签:
原文地址:http://www.cnblogs.com/tong775131501/p/5477137.html