C#編寫的一個反向 Proxy工具,可以緩衝網頁到本地

來源:互聯網
上載者:User
C#編寫的一個反向 Proxy工具,可以緩衝網頁到本地

proxy.ashx 主檔案

<%@ WebHandler Language="C#" Class="proxy" %>  using System;using System.Web;using System.Net;using System.Text;using System.IO;using System.Collections.Generic;using System.Configuration;      /// /// 把http headers 和 http 響應的內容 分別儲存在 /proxy/header/ 和 /proxy/body/ 中/// 分層次建立目錄/// public class proxy : IHttpHandler{      HttpResponse Response;    HttpRequest Request;    HttpApplicationState Application;    HttpServerUtility Server;      static string proxyCacheFolder = ConfigurationManager.AppSettings["proxyCacheFolder"];    static string proxyDomain = ConfigurationManager.AppSettings["proxyDomain"];    static string proxyReferer = ConfigurationManager.AppSettings["proxyReferer"];    bool proxyCacheDirectAccess = ConfigurationManager.AppSettings["proxyCacheDirectAccess"] == "true";    int proxyCacheSeconds = int.Parse(ConfigurationManager.AppSettings["proxyCacheSeconds"]);          public void ProcessRequest(HttpContext context)    {        Response = context.Response;        Request = context.Request;        Application = context.Application;        Server = context.Server;          string path = context.Request.RawUrl;        bool delCache = path.IndexOf("?del") > 0;        if (delCache)        {            path = path.Replace("?del", string.Empty);            DeleteCacheFile(path);            return;        }            bool allowCache = Request.QueryString["cache"] == "true";        string seconds = Request.QueryString["seconds"] ?? string.Empty;        if (!int.TryParse(seconds, out proxyCacheSeconds))        {            proxyCacheSeconds = 3600;        }          if (allowCache)        {              EchoData(path);        }        else        {              WebClient wc = new WebClient();            wc.Headers.Set("Referer", proxyReferer);            byte[] buffer = wc.DownloadData(proxyDomain + path);            Response.ContentType = wc.ResponseHeaders["Content-Type"];            foreach (string key in wc.ResponseHeaders.AllKeys)            {                  Response.Headers.Set(key, wc.ResponseHeaders[key]);            }            wc.Dispose();            Response.OutputStream.Write(buffer, 0, buffer.Length);        }          }        ///     /// 清理失效的緩衝    ///     ///     void ClearTimeoutCache(DirectoryInfo d)    {        if (d.Exists)        {            FileInfo[] files = d.GetFiles();            foreach (FileInfo file in files)            {                TimeSpan timeSpan = DateTime.Now - file.LastAccessTime;                if (timeSpan.TotalSeconds > proxyCacheSeconds)                {                    file.Delete();                }            }        }    }      string GetCacheFolderPath(string hash)    {        string s = string.Empty;        for (int i = 0; i <= 2; i++)        {            s += hash[i] + "/";        }          return s;    }      ///     /// 讀取緩衝的header 並輸出    ///     ///     void EchoCacheHeader(string cacheHeaderPath)    {        string[] headers = File.ReadAllLines(cacheHeaderPath);        for (int i = 0; i < headers.Length; i++)        {            string[] headerKeyValue = headers[i].Split(':');            if (headerKeyValue.Length == 2)            {                if (headerKeyValue[0] == "Content-Type")                {                    Response.ContentType = headerKeyValue[1];                }                Response.Headers.Set(headerKeyValue[0], headerKeyValue[1]);            }          }      }          void DeleteCacheFile(string path)    {        string absFolder = Server.MapPath(proxyCacheFolder);        string hash = GetHashString(path);          string folder = GetCacheFolderPath(hash);          string cacheBodyPath = absFolder + "/body/" + folder + hash;        string cacheHeaderPath = absFolder + "/header/" + folder + hash;          FileInfo cacheBody = new FileInfo(cacheBodyPath);        FileInfo cacheHeader = new FileInfo(cacheHeaderPath);          if (cacheBody.Exists)        {            cacheBody.Delete();        }          if (cacheHeader.Exists)        {            cacheHeader.Delete();        }          Response.Write("delete cache file Success!\r\n" + path);    }      ///     /// 輸出緩衝    ///     /// 緩衝header 的檔案路徑    /// 緩衝 body 的檔案路徑    /// 是否進行判斷檔案到期    /// 是否輸出成功    bool EchoCacheFile(string cacheHeaderPath, string cacheBodyPath, bool ifTimeout)    {        FileInfo cacheBody = new FileInfo(cacheBodyPath);        FileInfo cacheHeader = new FileInfo(cacheHeaderPath);          ClearTimeoutCache(cacheBody.Directory);        ClearTimeoutCache(cacheHeader.Directory);          if (cacheBody.Exists && cacheHeader.Exists)        {              if (ifTimeout)            {                TimeSpan timeSpan = DateTime.Now - cacheBody.LastWriteTime;                if (timeSpan.TotalSeconds < proxyCacheSeconds)                {                    EchoCacheHeader(cacheHeaderPath);                      Response.TransmitFile(cacheBodyPath);                    return true;                }            }            else            {                EchoCacheHeader(cacheHeaderPath);                  Response.TransmitFile(cacheBodyPath);                return true;            }          }          return false;    }      void EchoData(string path)    {          string absFolder = Server.MapPath(proxyCacheFolder);        string hash = GetHashString(path);          string folder = GetCacheFolderPath(hash);          string cacheBodyPath = absFolder + "/body/" + folder + hash;        string cacheHeaderPath = absFolder + "/header/" + folder + hash;          bool success;        if (proxyCacheDirectAccess)        {            success = EchoCacheFile(cacheHeaderPath, cacheBodyPath, false);            if (!success)            {                Response.Write("直接從緩衝讀取失敗!");            }            return;        }          success = EchoCacheFile(cacheHeaderPath, cacheBodyPath, true);          if (success)        {            return;        }                //更新Cache File        string ApplicationKey = "CacheList";        List List = null;            if (Application[ApplicationKey] == null)        {                       Application.Lock();            Application[ApplicationKey] = List = new List(1000);            Application.UnLock();        }        else        {              List = (List)Application[ApplicationKey];          }            //判斷是否已有另一個進程正在更新Cache File        if (List.Contains(hash))        {            success = EchoCacheFile(cacheHeaderPath, cacheBodyPath, false);            if (success)            {                return;            }            else            {                  WebClient wc = new WebClient();                wc.Headers.Set("Referer", proxyReferer);                //主體內容                byte[] data = wc.DownloadData(proxyDomain + path);                  //處理header                Response.ContentType = wc.ResponseHeaders["Content-Type"];                foreach (string key in wc.ResponseHeaders.AllKeys)                {                    Response.Headers.Set(key, wc.ResponseHeaders[key]);                }                wc.Dispose();                Response.BinaryWrite(data);                              }        }        else        {                               WebClient wc = new WebClient();            wc.Headers.Set("Referer", proxyReferer);            StringBuilder headersb = new StringBuilder();              List.Add(hash);            //主體內容            byte[] data = wc.DownloadData(proxyDomain + path);                      //處理header              Response.ContentType = wc.ResponseHeaders["Content-Type"];            foreach (string key in wc.ResponseHeaders.AllKeys)            {                headersb.Append(key);                headersb.Append(":");                headersb.Append(wc.ResponseHeaders[key]);                headersb.Append("\r\n");                Response.Headers.Set(key, wc.ResponseHeaders[key]);            }            wc.Dispose();              string headers = headersb.ToString().Trim();            if (!Directory.Exists(absFolder + "/header/" + folder))            {                Directory.CreateDirectory(absFolder + "/header/" + folder);            }              StreamWriter sw = File.CreateText(absFolder + "/header/" + folder + hash);            sw.Write(headers);            sw.Close();            sw.Dispose();                //處理緩衝內容            if (!Directory.Exists(absFolder + "/body/" + folder))            {                Directory.CreateDirectory(absFolder + "/body/" + folder);            }              FileStream fs = File.Create(absFolder + "/body/" + folder + hash);            fs.Write(data, 0, data.Length);            fs.Close();            fs.Dispose();              List.Remove(hash);                                        Response.BinaryWrite(data);        }    }            string GetHashString(string path)    {        string md5 = GetMd5Str(path);        return md5;    }        static string GetMd5Str(string ConvertString)    {        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();        string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);        t2 = t2.Replace("-", "");          return t2;    }        public bool IsReusable    {        get        {            return false;        }    }  }

web.config

                                          ~/.*$                          ~/proxy.ashx?cache=true&seconds=30                              ~/ajax/.*$                          ~/proxy.ashx?cache=false                                                                                                                                                  
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.