您的位置:首页 > 理论基础 > 计算机网络

图片防盗链之HttpHandler方法实现

2010-09-16 23:13 429 查看

图片防盗链之HttpHandler方法实现

作者:hayden 日期:2009-07-31

字体大小:












在网上搜索到了的答案都极其珍贵,这次,是关于.NET应用相关的,需要对图片相关文件进行防盗链,而又没有相关服务器的权限,不过幸好.net的功能很强大,足以满足各种需求了。

以下是摘抄了,基本上可以直接使用形的。

1:创建文件 CustomHandler.cs,代码如下:

复制内容到剪贴板

程序代码
using System;
using System.Web;

namespace CustomHandler{
public class JpgHandler : IHttpHandler{
public void ProcessRequest(HttpContext context){
// 获取文件服务器端物理路径
string FileName = context.Server.MapPath(context.Request.FilePath);
// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host == null){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}else{
// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}

public bool IsReusable{
get{ return true; }
}
}
}

2 编译这个文件


引用内容
csc /t:library /r:System.Web.DLL CustomHandler.cs

3 将编译好的 CustomHandler.DLL 拷贝到站点的 Bin 目录下。

4 在Web.Config 中注册这个Handler。

复制内容到剪贴板

程序代码
<system.web>
<httpHandlers>
<add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
</httpHandlers>
</system.web>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: