防盗链IHttpHandler
*
* 防盗链IHttpHandler
*
*
* 增加了对文件关键字的选择(即仅对文件名存在某些关键字或不存在某些关键字进行过滤)
* 设置web.config中<appSettings>节以下值
* string eWebapp_NoLink 如果文件名符合该正确表态式将进行过滤(不设置对所有进行过滤)
* string eWebapp_AllowLink 如果文件名符合该正确表态式将不进行过滤(优先权高于AllowLink,不设置则服从AllowLink)
* bool eWebapp_ AllowOnlyFile 如果为False,(默认true)则不允许用户直接对该文件进行访问建议为true
*
*
* :)以下设置均可省略,设置只是为了增加灵活性与体验
* eWebapp_NoLink_Message 错误信息提示:默认为Link From:域名
* eWebapp_Error_Width 错误信息提示图片宽
* eWebapp_Error_Height 错误信息提示图片高
*
*
*
* 垃圾猪 2005-9-11 创建
* http://ewebapp.net
*/
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;
namespace eWebapp
{
/// <summary>
/// 防盗链IHttpHandler
/// 参考http://www.softat.org/archiver/tid-52114.html
/// 垃圾猪 2005-9-12 修正
/// </summary>
public class NoLink : IHttpHandler
{
private string eWebapp_NoLink = string.Empty;
private string eWebapp_AllowLink = string.Empty;
private bool eWebapp_AllowOnlyFile = true;
private string eWebapp_NoLink_Message = string.Empty;
private bool error = false;
public NoLink()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ProcessRequest(HttpContext context)
{
eWebapp_NoLink_Message = ConfigurationSettings.AppSettings["eWebapp_NoLink_Message"];
string myDomain = string.Empty;
error = errorLink(context,out myDomain);
if(Empty(eWebapp_NoLink_Message))
{
eWebapp_NoLink_Message = "Link from :" + myDomain;
}
if(error)
{
//Jpg(context.Response,eWebapp_NoLink_Message);
Jpg(context.Response,eWebapp_NoLink_Message);
}
else
{
Real(context.Response,context.Request);
}
}
public bool IsReusable
{
get
{
return true;
}
}
/// <summary>
/// 输出错误信息
/// </summary>
/// <param name="Response"></param>
/// <param name="_word"></param>
private void Jpg(HttpResponse Response,string _word)
{
int myErrorWidth = _word.Length*15;
int myErrorHeight = 16;
try
{
int _myErrorWidth = Convert.ToInt32(ConfigurationSettings.AppSettings["eWebapp_Error_Width"]);
if(_myErrorWidth > 0 )
{
myErrorWidth = _myErrorWidth;
}
}
catch
{
}
try
{
int _myErrorHeight = Convert.ToInt32(ConfigurationSettings.AppSettings["eWebapp_Error_Height"]);
if(_myErrorHeight > 0 )
{
myErrorHeight = _myErrorHeight;
}
}
catch
{
}
Bitmap Img=null;
Graphics g=null;
MemoryStream ms=null;
Img=new Bitmap(myErrorWidth,myErrorHeight);
g=Graphics.FromImage(Img);
g.Clear(Color.White);
Font f=new Font("Arial",9);
SolidBrush s=new SolidBrush(Color.Red);
g.DrawString(_word,f,s,3,3);
ms=new MemoryStream();
Img.Save(ms,ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType="image/Gif";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
/// <summary>
/// 输出真实文件
/// </summary>
/// <param name="response"></param>
/// <param name="context"></param>
private void Real(HttpResponse response,HttpRequest request)
{
FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
response.Clear();
response.AddHeader("Content-Disposition", "filename=" + file.Name);
response.AddHeader("Content-Length", file.Length.ToString());
string fileExtension = file.Extension.ToLower();
//这里选择输出的文件格式
//可以参考http://ewebapp.cnblogs.com/articles/234756.html增加对更多文件格式的支持.
switch (fileExtension)
{
case "mp3":
response.ContentType = "audio/mpeg3";
break;
case "mpeg":
response.ContentType = "video/mpeg";
break;
case "jpg":
response.ContentType = "image/jpeg";
break;
case "bmp":
response.ContentType = "image/bmp";
break;
case "gif":
response.ContentType = "image/gif";
break;
case "doc":
response.ContentType = "application/msword";
break;
case "css":
response.ContentType = "text/css";
break;
default:
response.ContentType = "application/octet-stream";
break;
}
response.WriteFile(file.FullName);
response.End();
}
/// <summary>
/// 确认字符串是否为空
/// </summary>
/// <param name="_value"></param>
/// <returns></returns>
private bool Empty(string _value)
{
if(_value == null | _value == string.Empty | _value == "")
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 检查是否是非法链接
/// </summary>
/// <param name="context"></param>
/// <param name="_myDomain"></param>
/// <returns></returns>
private bool errorLink(HttpContext context,out string _myDomain)
{
HttpResponse response = context.Response;
string myDomain = context.Request.ServerVariables["SERVER_NAME"];
_myDomain = myDomain ;
string myDomainIp = context.Request.UserHostAddress;
eWebapp_NoLink = ConfigurationSettings.AppSettings["eWebapp_NoLink"];
eWebapp_AllowLink = ConfigurationSettings.AppSettings["eWebapp_AllowLink"];
try
{
eWebapp_AllowOnlyFile = Convert.ToBoolean(ConfigurationSettings.AppSettings["eWebapp_AllowOnlyFile"]);
}
catch
{
eWebapp_AllowOnlyFile = true;
}
if(context.Request.UrlReferrer != null)
{
//判定referDomain是否存在网站的IP或域名
string referDomain = context.Request.UrlReferrer.AbsoluteUri.Replace(context.Request.UrlReferrer.AbsolutePath,"");
string myPath = context.Request.RawUrl;
if(referDomain.IndexOf(myDomainIp) >=0 | referDomain.IndexOf(myDomain)>=0)
{
return false;
}
else
{
//这里使用正则表达对规则进行匹配
try
{
Regex myRegex ;
//检查允许匹配
if(!Empty(eWebapp_AllowLink))
{
myRegex = new Regex(eWebapp_AllowLink);
if(myRegex.IsMatch(myPath))
{
return false;
}
}
//检查禁止匹配
if(!Empty(eWebapp_NoLink))
{
myRegex = new Regex(eWebapp_NoLink);
if(myRegex.IsMatch(myPath))
{
return true;
}
else
{
return false;
}
}
return true;
}
catch
{
//如果匹配出错,链接错误
return true;
}
}
}
else
{
//是否允许直接访问文件
if(eWebapp_AllowOnlyFile)
{
return false;
}
else
{
return true;
}
}
}
}
}
转贴
转载于:https://www.cnblogs.com/eidolon8/archive/2007/07/26/831939.html
防盗链IHttpHandler相关推荐
- ASP.NET 防盗链源码
防盗链原理: http标准协议中有专门的字段记录referer 一来可以追溯上一个入站地址是什么 二来对于资源文件,可以跟踪到包含显示他的网页地址是什么. 因此所有防盗链方法都是基于这个Referer ...
- IHttpHandler的妙用之防盗链
昨天粗略讲了一下IHttpHandler接口的作用和动态给图片添加水印的处理,如果对这些不太清除的朋友,建议看看这篇<IHttpHandler的妙用(1):给图片添加水印>:http:// ...
- IHttpHandler的妙用(2):防盗链!我的资源只有我的用户才能下载
昨天粗略讲了一下IHttpHandler接口的作用和动态给图片添加水印的处理,如果对这些不太清除的朋友,建议看看这篇<IHttpHandler的妙用(1):给图片添加水印>:http:// ...
- ASP.NET中利用ashx实现图片防盗链
盗链的危害我就不说了,网上有很多. 直接分析盗链原理:看下面用httpwatch截获的http发送的数据 GET /Img.ashx?img=svn_work.gif HTTP/1.1 Accept: ...
- 第十三节:HttpHander扩展及应用(自定义扩展名、图片防盗链)
一. 自定义扩展名 1. 前言 凡是实现了IHttpHandler接口的类均为Handler类,HttpHandler是一个HTTP请求的真正处理中心,在HttpHandler容器中,ASP.NET ...
- 网站防盗链就是那么简单
第一步 : 实现 IHttpHandler 接口 namespace WebHotlinkProtection { public class HotlinkProtectionHandler:IHtt ...
- ATS中开启Refer防盗链功能
ATS默认提供了对Referer头的http request的防盗链功能,主要应用于图片,对视频等会使用级别更高的防盗链功能,比如事先约定好key,采用md5或HMAC-Sha1算法加密等. 在rem ...
- Linux-LNMP(静态元素不记录日志和过期时间,防盗链,解析php,代理,支持ssl)
Linux-LNMP-Nginx配置二 静态文件不记录日志和过期时间 Nginx防盗链 Nginx访问控制 Nginx解析php相关配置 Nginx代理 Nginx负载均衡 SSL原理 生成SSL密钥 ...
- Nginx防盗链,Nginx访问控制, Nginx解析php相关配置, Nginx代理
2019独角兽企业重金招聘Python工程师标准>>> Nginx防盗链 Nginx防盗链配置需要与不记录日志和过期时间结合在一起,因为都用到了location. 打开配置文件,注释 ...
最新文章
- c++矩阵类_Python线性代数学习笔记——矩阵的基本运算和基本性质,实现矩阵的基本运算...
- java shape用法_Java PShape.scale方法代码示例
- 如何让 Drupal 使用 Wordpress 形式的编辑代码?
- 03数据库的基本查询
- 【Spark】Spark Stream读取kafka写入kafka报错 AbstractMethodError
- R语言CRAN软件包Meta分析 1
- 浅谈数据结构之顺序队列(五)
- Thrift原理与使用实例
- 人脸方向学习(十二):Face Detection-Tiny-DSOD解读
- java 枚举 映射_java – 如何将值映射到枚举?
- TM1640 数码管驱动代码(简化版)
- 实现导航栏的几种方式
- 谷歌Chrome浏览器的翻译按钮不见了
- 对RAM,ROM,NOR/NAND FLASH等常见内存设备类型的理解
- 安装程序无法继续因为计算机上安,Windows安装无法继续怎么办?Windows安装无法继续的解决方法...
- An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling
- “奔驰车主哭诉维权”续:双方再次协商无果
- andorid开发关键技术
- 开源软件之许可证(三)
- 【Shell秒懂系列】引用及转义(单引号/双引号/反斜杠/反引号)
热门文章
- 与图片相关的几个库的编译
- insert 数组_Java数组和集合的效率问题
- 【Elasticsearch】ES内存满问题排查思路
- 【Kafka】Kafka 配置 SASL_SSL jks鉴权验证方式
- Spark报错:JDOFatalInternalException: Error creating transactional connection factory
- spark学习-67-源代码:schedulerBackend和taskScheduler的总结
- SpringBoot : Spring容器生命周期管理:SmartLifecycle
- Kudu : 三种Fulsh Mode
- Rabbitmq的三种方式
- 处理 git 合并冲突