龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

ASP.NET网站使用HttpHandler实现图片防盗链功能

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
网站的图片给盗链是不是觉得很头痛呢?下面方法使用.NET的HttpHandler来实现图片防盗链. 第一步:创建文件 CustomHandler.cs,代码如下: using System; using System.Web; namespace CustomHandler{ public

网站的图片给盗链是不是觉得很头痛呢?下面方法使用.NET的HttpHandler来实现图片防盗链.

第一步:创建文件 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; }
       }
    }
}

第二步 编译这个文件(这个文件也可以直接在项目生成发布,就不会运行下面命令了)

csc /t:library /r:System.Web.dll CustomHandler.cs

第三步 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。

第四步 在Web.Config 中注册这个Handler。

<system.web>
    <httpHandlers>
      <add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
    </httpHandlers>
</system.web>

第五步:在IIS配置(如下图)

上图可执行文件路径为:

c:windowsmicrosoft.netframeworkv2.0.50727aspnet_isapi.dll

 

精彩图集

赞助商链接