BlackIpModule.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. using System.Collections;
  12. using System.Web.Caching;
  13. using System.Configuration;
  14. using System.Web.UI;
  15. using Common;
  16. namespace CB.Common
  17. {
  18. public class BlackIpHttpModule : Page, IHttpModule
  19. {
  20. static readonly WebCache cache = new WebCache();
  21. public void Dispose() { }
  22. public void Init(HttpApplication application)
  23. {
  24. application.BeginRequest += new EventHandler(Application_BeginRequest);
  25. }
  26. private void Application_BeginRequest(object sender, EventArgs e)
  27. {
  28. HttpApplication application = (HttpApplication)sender;
  29. //using (var sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ipaddress.txt"), true, System.Text.Encoding.Default))
  30. //{
  31. // sw.WriteLine("Ip => " + IPAddress);
  32. // sw.Flush();
  33. //}
  34. if (BlackIPs.Any(ip => ip == IPAddress))
  35. {
  36. application.Context.Response.Write("禁止访问");
  37. application.Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
  38. application.CompleteRequest();
  39. }
  40. if (null != Thread.CurrentThread.Name)
  41. {
  42. return;
  43. }
  44. try
  45. {
  46. var request = application.Context.Request;
  47. if (ConfigurationManager.AppSettings["IsOpenIntercept"] == "true")
  48. {
  49. var ip = GetWebClientIp(request);
  50. var key = "ProhibitIP";
  51. var data = cache.GetObject<List<string>>(key);
  52. if (data == null)
  53. {
  54. data = VisitIPDAL.GetProhibitIP();
  55. cache.AddObject(key, data);
  56. }
  57. if (data.Contains(ip))
  58. HttpContext.Current.Response.Redirect(ConfigurationManager.AppSettings["InterceptView"], true);
  59. else
  60. VisitIPDAL.AddActionFilterLog(request.Url.ToString(), ip);
  61. }
  62. else
  63. {
  64. var ip = GetWebClientIp(request);
  65. VisitIPDAL.AddActionFilterLog(request.Url.ToString(), ip);
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. LogHelper.Error(typeof(BlackIpHttpModule), ex.Message);
  71. }
  72. }
  73. public static string IPAddress
  74. {
  75. get
  76. {
  77. string userIP;
  78. // HttpRequest Request = HttpContext.Current.Request;
  79. HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request;
  80. // 如果使用代理,获取真实IP
  81. if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
  82. userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  83. else
  84. userIP = Request.ServerVariables["REMOTE_ADDR"];
  85. if (userIP == null || userIP == "")
  86. userIP = Request.UserHostAddress;
  87. return userIP;
  88. }
  89. }
  90. private volatile static List<string> _blacklist = null;
  91. public List<string> BlackIPs
  92. {
  93. get
  94. {
  95. if (_blacklist == null)
  96. {
  97. _blacklist = new List<string>();
  98. string s = System.Configuration.ConfigurationManager.AppSettings["blackips"];
  99. if (!string.IsNullOrEmpty(s))
  100. {
  101. _blacklist.AddRange(s.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
  102. }
  103. }
  104. return _blacklist;
  105. }
  106. }
  107. /// <summary>
  108. /// 获取Web客户端的Ip
  109. /// </summary>
  110. private static string GetWebClientIp(HttpRequest request)
  111. {
  112. var ip = "";
  113. if (request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR"))
  114. ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.ServerVariables["REMOTE_ADDR"];
  115. else
  116. ip = request.ServerVariables["REMOTE_ADDR"];
  117. foreach (var hostAddress in Dns.GetHostAddresses(ip))
  118. {
  119. if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
  120. {
  121. return hostAddress.ToString();
  122. }
  123. else
  124. {
  125. return ip == "::1" ? "127.0.0.1" : ip;
  126. }
  127. }
  128. return string.Empty;
  129. }
  130. }
  131. /// <summary>
  132. /// 默认的.net WebCache接口实现
  133. /// </summary>
  134. public class WebCache
  135. {
  136. protected static volatile System.Web.Caching.Cache webCache = HttpRuntime.Cache;
  137. /// <summary>
  138. /// 判断值是否存在..
  139. /// </summary>
  140. /// <param name="key"></param>
  141. /// <returns></returns>
  142. public bool IsExist(string key)
  143. {
  144. if (string.IsNullOrEmpty(key))
  145. return false;
  146. return webCache[key] != null;
  147. }
  148. /// <summary>
  149. /// 写入某个Cache
  150. /// </summary>
  151. /// <param name="key">键</param>
  152. /// <param name="o">对像</param>
  153. public void AddObject<T>(string key, T o, int t = 0)
  154. {
  155. if (String.IsNullOrEmpty(key) || o == null)
  156. return;
  157. if (t == 0)
  158. t = int.Parse(ConfigurationManager.AppSettings["OutTime"]);
  159. CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);
  160. webCache.Insert(key, o, null, System.DateTime.Now.AddMinutes(t), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack);
  161. }
  162. /// <summary>
  163. /// 取某个key对应的object值
  164. /// </summary>
  165. /// <param name="key">键</param>
  166. /// <returns></returns>
  167. public T GetObject<T>(string key)
  168. {
  169. if (!String.IsNullOrEmpty(key))
  170. return (T)webCache.Get(key);
  171. return default(T);
  172. }
  173. /// <summary>
  174. /// 移出某个Cache
  175. /// </summary>
  176. /// <param name="key">键</param>
  177. public void RemoveObject(string key)
  178. {
  179. if (!String.IsNullOrEmpty(key))
  180. webCache.Remove(key);
  181. }
  182. /// <summary>
  183. /// 批量移出类型key的对像
  184. /// </summary>
  185. /// <param name="key"></param>
  186. public void RemoveObjectByRegex(string pattern)
  187. {
  188. if (!string.IsNullOrEmpty(pattern))
  189. {
  190. IDictionaryEnumerator enu = webCache.GetEnumerator();
  191. while (enu.MoveNext())
  192. {
  193. string key = enu.Key.ToString();
  194. if (key.IndexOf(pattern, StringComparison.CurrentCultureIgnoreCase) != -1)
  195. {
  196. RemoveObject(key);
  197. }
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// 移出所有Cache
  203. /// </summary>
  204. public void RemoveAll()
  205. {
  206. IDictionaryEnumerator enu = webCache.GetEnumerator();
  207. while (enu.MoveNext())
  208. {
  209. RemoveObject(enu.Key.ToString());
  210. }
  211. }
  212. public void onRemove(string key, object val, CacheItemRemovedReason reason)
  213. {
  214. switch (reason)
  215. {
  216. case CacheItemRemovedReason.DependencyChanged:
  217. //更新缓存映射表
  218. break;
  219. case CacheItemRemovedReason.Expired:
  220. //更新缓存映射表
  221. break;
  222. case CacheItemRemovedReason.Removed:
  223. break;
  224. case CacheItemRemovedReason.Underused:
  225. break;
  226. default:
  227. break;
  228. }
  229. }
  230. /// <summary>
  231. /// 返回所有键值
  232. /// </summary>
  233. /// <returns></returns>
  234. public List<string> GetKeys()
  235. {
  236. List<string> list = new List<string>();
  237. IDictionaryEnumerator enu = webCache.GetEnumerator();
  238. while (enu.MoveNext())
  239. {
  240. list.Add(enu.Key.ToString());
  241. }
  242. return list;
  243. }
  244. }
  245. }