开源Asp.Net论坛

阿强.Net

关注研究:设计模式,.Net Framework底层框架,Asp.net,WinForm开发,开源框架;

导航

C#图片防盗链

1 写一个继承自IHttpHandler的类,并生成DLL;
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;

namespace ImgProtect
{
    public class ImgProtectHadler:IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Request.PhysicalPath;
            string serverHost = context.Request.Url.Host;
            Uri u = context.Request.UrlReferrer;
            if (u == null || u.Host.ToLower() != serverHost.ToLower())
            {
                context.Response.WriteFile("~/Forbidden.gif");
            }
            else
            {
                context.Response.WriteFile(path);
            }
        }

    }
}
2 在网站中引用 该DLL;

3 在Web.config中加入

<httpHandlers>
   <add verb="*" path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" type="ImgProtect.ImgProtectHadler"/>
  </httpHandlers>


posted on 2008-02-25 22:33  阿强.Net  阅读(2701)  评论(1编辑  收藏  举报