123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- 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<List<string>>(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<string> _blacklist = null;
- public List<string> BlackIPs
- {
- get
- {
- if (_blacklist == null)
- {
- _blacklist = new List<string>();
- string s = System.Configuration.ConfigurationManager.AppSettings["blackips"];
- if (!string.IsNullOrEmpty(s))
- {
- _blacklist.AddRange(s.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
- }
- }
- return _blacklist;
- }
- }
- /// <summary>
- /// 获取Web客户端的Ip
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 默认的.net WebCache接口实现
- /// </summary>
- public class WebCache
- {
- protected static volatile System.Web.Caching.Cache webCache = HttpRuntime.Cache;
- /// <summary>
- /// 判断值是否存在..
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool IsExist(string key)
- {
- if (string.IsNullOrEmpty(key))
- return false;
- return webCache[key] != null;
- }
- /// <summary>
- /// 写入某个Cache
- /// </summary>
- /// <param name="key">键</param>
- /// <param name="o">对像</param>
- public void AddObject<T>(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);
- }
- /// <summary>
- /// 取某个key对应的object值
- /// </summary>
- /// <param name="key">键</param>
- /// <returns></returns>
- public T GetObject<T>(string key)
- {
- if (!String.IsNullOrEmpty(key))
- return (T)webCache.Get(key);
- return default(T);
- }
- /// <summary>
- /// 移出某个Cache
- /// </summary>
- /// <param name="key">键</param>
- public void RemoveObject(string key)
- {
- if (!String.IsNullOrEmpty(key))
- webCache.Remove(key);
- }
- /// <summary>
- /// 批量移出类型key的对像
- /// </summary>
- /// <param name="key"></param>
- 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);
- }
- }
- }
- }
- /// <summary>
- /// 移出所有Cache
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 返回所有键值
- /// </summary>
- /// <returns></returns>
- public List<string> GetKeys()
- {
- List<string> list = new List<string>();
- IDictionaryEnumerator enu = webCache.GetEnumerator();
- while (enu.MoveNext())
- {
- list.Add(enu.Key.ToString());
- }
- return list;
- }
- }
- }
|