BlackIpModule.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. namespace CB.Common
  8. {
  9. public class BlackIpHttpModule : IHttpModule
  10. {
  11. public void Dispose() { }
  12. public void Init(HttpApplication application)
  13. {
  14. application.BeginRequest += new EventHandler(Application_BeginRequest);
  15. }
  16. private void Application_BeginRequest(object sender, EventArgs e)
  17. {
  18. HttpApplication application = (HttpApplication)sender;
  19. //using (var sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ipaddress.txt"), true, System.Text.Encoding.Default))
  20. //{
  21. // sw.WriteLine("Ip => " + IPAddress);
  22. // sw.Flush();
  23. //}
  24. if (BlackIPs.Any(ip => ip == IPAddress))
  25. {
  26. application.Context.Response.Write("禁止访问");
  27. application.Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
  28. application.CompleteRequest();
  29. }
  30. }
  31. public static string IPAddress
  32. {
  33. get
  34. {
  35. string userIP;
  36. // HttpRequest Request = HttpContext.Current.Request;
  37. HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request;
  38. // 如果使用代理,获取真实IP
  39. if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
  40. userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  41. else
  42. userIP = Request.ServerVariables["REMOTE_ADDR"];
  43. if (userIP == null || userIP == "")
  44. userIP = Request.UserHostAddress;
  45. return userIP;
  46. }
  47. }
  48. private volatile static List<string> _blacklist = null;
  49. public List<string> BlackIPs
  50. {
  51. get
  52. {
  53. if (_blacklist == null)
  54. {
  55. _blacklist = new List<string>();
  56. string s = System.Configuration.ConfigurationManager.AppSettings["blackips"];
  57. if (!string.IsNullOrEmpty(s))
  58. {
  59. _blacklist.AddRange(s.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
  60. }
  61. }
  62. return _blacklist;
  63. }
  64. }
  65. }
  66. }