今天看书时发现一个实现asp.net 2.0中实现防止盗链的方法,其实际的原理就是利用了IIS中HttpHandler模块来处理的。因为比如
平时用IIS只是处理如asp,aspx等文件,没处理如iis,jpg等图片的,下面简单小结下

1 建一个网站(vs.net 2005),然后添加一个Handler.ashx处理文件,处理HTTP请求,代码如下
  <%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        //判断是否是本地引用,如果是则返回给客户端正确的图片
        //这里的判断就是用到了http请求中所记录的页信息
        //如果是网站,可将“localhost”修改为网站地址
        if (context.Request.UrlReferrer.Host == "localhost")
        {
            //设置客户端缓冲中文件过期时间为0,即立即过期。
            context.Response.Expires = 0;
            //清空服务器端为此会话开辟的输出缓存
            context.Response.Clear();
            //获得文件类型
            context.Response.ContentType = "image/jpg";
            //将请求文件写入到输出缓存中
            context.Response.WriteFile(context.Request.PhysicalPath);
            //将输出缓存中的信息传送到客户端
            context.Response.End();
        }
        //如果不是本地引用,则属于盗链引用,返回给客户端错误的图片
        else
        {
            //设置客户端缓冲中文件过期时间为0,即立即过期。
            context.Response.Expires = 0;
            //清空服务器端为此会话开辟的输出缓存
            context.Response.Clear();
            //获得文件类型
            context.Response.ContentType = "image/jpg";
            //将特殊的报告错误的图片文件写入到输出缓存中
            context.Response.WriteFile(context.Request.PhysicalApplicationPath + "error.jpg");
            //将输出缓存中的信息传送到客户端
            context.Response.End();
        }
    }
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}
 然后同样建立一个Handler.cs文件,放在app_code目录下,其内容就是上面的handler.aschx了,
2  在web.config中配置如下
    <httpHandlers>
   <add verb = "*" path = "*.jpg"   type="Handler" />
  </httpHandlers>


3  在IIS里处理
    在IIS里的默认网站的“配置”里,在“应用程序映射”里添加映射
其中映射的可执行文件为  “vs.net2005安装路径\aspnet_isapi.dll",扩展名为".jpg",这样就可以了

posted on 2007-05-16 07:41  站在天空下的猪  阅读(223)  评论(0编辑  收藏  举报