欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

C#编写的一个反向代理工具,可以缓存网页到本地

程序员文章站 2022-04-19 08:51:01
...
C#编写的一个反向代理工具,可以缓存网页到本地

proxy.ashx 主文件

  
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 
    /// 读取缓存的header 并输出
    /// 
    /// 
    void EchoCacheHeader(string cacheHeaderPath)
    {
        string[] headers = File.ReadAllLines(cacheHeaderPath);
        for (int i = 0; i 
    /// 输出缓存
    /// 
    /// 缓存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  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

~/.*$~/ajax/.*$