0

0

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

大家讲道理

大家讲道理

发布时间:2016-11-10 16:25:25

|

2369人浏览过

|

来源于php中文网

原创

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

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

Redo Rescue: Backup and Recovery
Redo Rescue: Backup and Recovery

Redo Rescue备份和恢复可以在几分钟内备份和恢复整个系统,使用点-and-click界面,任何人都可以使用。裸机恢复到一个新的、空白的驱动器上,几分钟内即可启动和运行。支持保存和恢复到本地磁盘或共享网络驱动器。选择性地恢复分区并将其重新映射到目标驱动器上的不同位置。附带其他工具用于分区编辑、网页浏览等。从live CD/USB运行,无需安装。网站:http://redorescue.com论坛:https://sourceforge.net/p/redobackup/discussion/GitH

下载


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

相关专题

更多
高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

4

2026.01.16

全民K歌得高分教程大全
全民K歌得高分教程大全

本专题整合了全民K歌得高分技巧汇总,阅读专题下面的文章了解更多详细内容。

3

2026.01.16

C++ 单元测试与代码质量保障
C++ 单元测试与代码质量保障

本专题系统讲解 C++ 在单元测试与代码质量保障方面的实战方法,包括测试驱动开发理念、Google Test/Google Mock 的使用、测试用例设计、边界条件验证、持续集成中的自动化测试流程,以及常见代码质量问题的发现与修复。通过工程化示例,帮助开发者建立 可测试、可维护、高质量的 C++ 项目体系。

10

2026.01.16

java数据库连接教程大全
java数据库连接教程大全

本专题整合了java数据库连接相关教程,阅读专题下面的文章了解更多详细内容。

33

2026.01.15

Java音频处理教程汇总
Java音频处理教程汇总

本专题整合了java音频处理教程大全,阅读专题下面的文章了解更多详细内容。

15

2026.01.15

windows查看wifi密码教程大全
windows查看wifi密码教程大全

本专题整合了windows查看wifi密码教程大全,阅读专题下面的文章了解更多详细内容。

42

2026.01.15

浏览器缓存清理方法汇总
浏览器缓存清理方法汇总

本专题整合了浏览器缓存清理教程汇总,阅读专题下面的文章了解更多详细内容。

7

2026.01.15

ps图片相关教程汇总
ps图片相关教程汇总

本专题整合了ps图片设置相关教程合集,阅读专题下面的文章了解更多详细内容。

9

2026.01.15

ppt一键生成相关合集
ppt一键生成相关合集

本专题整合了ppt一键生成相关教程汇总,阅读专题下面的的文章了解更多详细内容。

6

2026.01.15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.7万人学习

Kotlin 教程
Kotlin 教程

共23课时 | 2.6万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号