• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > C#实现可缓存网页到本地的反向代理工具实例

C#实现可缓存网页到本地的反向代理工具实例

作者:songguo 字体:[增加 减小] 来源:互联网 时间:2017-05-28

songguo 通过本文主要向大家介绍了C#实现可缓存网页到本地的反向代理工具实例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文实例讲述了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;
/// <summary>
/// 把http headers 和 http 响应的内容 分别存储在 /proxy/header/ 和 /proxy/body/ 中
/// 分层次创建目录
/// </summary>
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);
  }
 }
 /// <summary>
 /// 清理失效的缓存
 /// </summary>
 /// <param name="d"></param>
 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;
 }
 /// <summary>
 /// 读取缓存的header 并输出
 /// </summary>
 /// <param name="cacheHeaderPath"></param>
 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);
 }
 /// <summary>
 /// 输出缓存
 /// </summary>
 /// <param name="cacheHeaderPath">缓存header 的文件路径</param>
 /// <param name="cacheBodyPath">缓存 body 的文件路径</param>
 /// <param name="ifTimeout">是否进行判断文件过期</param>
 /// <returns>是否输出成功</returns>
 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<string> List = null;
  if (Application[ApplicationKey] == null)
  {   
   Application.Lock();
   Application[ApplicationKey] = List = new List<string>(1000);
   Application.UnLock();
  }
  else
  {
   List = (List<string>)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)
 {
  str



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

相关文章

  • 2017-05-28WinForm中comboBox控件数据绑定实现方法
  • 2017-05-28浅谈C#2.0泛型中的变化:default关键字
  • 2017-05-28C#如何动态设置屏幕分辨率
  • 2017-05-28silverlight实现图片局部放大效果的方法
  • 2017-05-28C#难点逐个击破(3):params数组参数
  • 2017-05-28C#中Try-Catch语句真的影响程序性能吗?
  • 2017-05-28C#利用Random得随机数求均值、方差、正态分布的方法
  • 2017-05-28C#设置输入法实例分析
  • 2017-05-28C#批量插入数据到Sqlserver中的三种方式
  • 2017-05-28c# Form中的键盘响应具体实现思路

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C#实现大数字运算的实例代码
    • C#中使用ADOMD.NET查询多维数据集的实现方法
    • 经典排序算法之冒泡排序(Bubble sort)代码
    • C#获取系统版本信息方法
    • C# Access数据库增删查改的简单方法
    • C#调用CMD命令实例
    • c#操作sql server2008 的界面实例代码
    • c# 冒泡排序算法(Bubble Sort) 附实例代码
    • C#实现图片加相框的方法
    • C#位移的介绍与例子

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有