using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.IO; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections; using System.Web.Caching; using System.Configuration; using System.Web.UI; using Common; namespace CB.Common { public class BlackIpHttpModule : Page, IHttpModule { static readonly WebCache cache = new WebCache(); public void Dispose() { } public void Init(HttpApplication application) { application.BeginRequest += new EventHandler(Application_BeginRequest); } private void Application_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; //using (var sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ipaddress.txt"), true, System.Text.Encoding.Default)) //{ // sw.WriteLine("Ip => " + IPAddress); // sw.Flush(); //} if (BlackIPs.Any(ip => ip == IPAddress)) { application.Context.Response.Write("禁止访问"); application.Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; application.CompleteRequest(); } if (null != Thread.CurrentThread.Name) { return; } try { var request = application.Context.Request; if (ConfigurationManager.AppSettings["IsOpenIntercept"] == "true") { var ip = GetWebClientIp(request); var key = "ProhibitIP"; var data = cache.GetObject>(key); if (data == null) { data = VisitIPDAL.GetProhibitIP(); cache.AddObject(key, data); } if (data.Contains(ip)) HttpContext.Current.Response.Redirect(ConfigurationManager.AppSettings["InterceptView"], true); else VisitIPDAL.AddActionFilterLog(request.Url.ToString(), ip); } else { var ip = GetWebClientIp(request); VisitIPDAL.AddActionFilterLog(request.Url.ToString(), ip); } } catch (Exception ex) { LogHelper.Error(typeof(BlackIpHttpModule), ex.Message); } } public static string IPAddress { get { string userIP; // HttpRequest Request = HttpContext.Current.Request; HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request; // 如果使用代理,获取真实IP if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "") userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; else userIP = Request.ServerVariables["REMOTE_ADDR"]; if (userIP == null || userIP == "") userIP = Request.UserHostAddress; return userIP; } } private volatile static List _blacklist = null; public List BlackIPs { get { if (_blacklist == null) { _blacklist = new List(); string s = System.Configuration.ConfigurationManager.AppSettings["blackips"]; if (!string.IsNullOrEmpty(s)) { _blacklist.AddRange(s.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); } } return _blacklist; } } /// /// 获取Web客户端的Ip /// private static string GetWebClientIp(HttpRequest request) { var ip = ""; if (request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR")) ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.ServerVariables["REMOTE_ADDR"]; else ip = request.ServerVariables["REMOTE_ADDR"]; foreach (var hostAddress in Dns.GetHostAddresses(ip)) { if (hostAddress.AddressFamily == AddressFamily.InterNetwork) { return hostAddress.ToString(); } else { return ip == "::1" ? "127.0.0.1" : ip; } } return string.Empty; } } /// /// 默认的.net WebCache接口实现 /// public class WebCache { protected static volatile System.Web.Caching.Cache webCache = HttpRuntime.Cache; /// /// 判断值是否存在.. /// /// /// public bool IsExist(string key) { if (string.IsNullOrEmpty(key)) return false; return webCache[key] != null; } /// /// 写入某个Cache /// /// 键 /// 对像 public void AddObject(string key, T o, int t = 0) { if (String.IsNullOrEmpty(key) || o == null) return; if (t == 0) t = int.Parse(ConfigurationManager.AppSettings["OutTime"]); CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove); webCache.Insert(key, o, null, System.DateTime.Now.AddMinutes(t), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack); } /// /// 取某个key对应的object值 /// /// 键 /// public T GetObject(string key) { if (!String.IsNullOrEmpty(key)) return (T)webCache.Get(key); return default(T); } /// /// 移出某个Cache /// /// 键 public void RemoveObject(string key) { if (!String.IsNullOrEmpty(key)) webCache.Remove(key); } /// /// 批量移出类型key的对像 /// /// public void RemoveObjectByRegex(string pattern) { if (!string.IsNullOrEmpty(pattern)) { IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { string key = enu.Key.ToString(); if (key.IndexOf(pattern, StringComparison.CurrentCultureIgnoreCase) != -1) { RemoveObject(key); } } } } /// /// 移出所有Cache /// public void RemoveAll() { IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { RemoveObject(enu.Key.ToString()); } } public void onRemove(string key, object val, CacheItemRemovedReason reason) { switch (reason) { case CacheItemRemovedReason.DependencyChanged: //更新缓存映射表 break; case CacheItemRemovedReason.Expired: //更新缓存映射表 break; case CacheItemRemovedReason.Removed: break; case CacheItemRemovedReason.Underused: break; default: break; } } /// /// 返回所有键值 /// /// public List GetKeys() { List list = new List(); IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { list.Add(enu.Key.ToString()); } return list; } } }