【IT168技术文档】
1. web.config配置
在config的<httpHandlers></httpHandlers>节点加入:
<add verb="*" path="*.gif,*.jpg,*.png" type="ImgProtector.BLL.SiteImgProtector"/>
verb:* 表示对所有http请求方式进行处理
path:*.gif,*.jpg,*.png,表示处理所有站点的gif/jgp/png文件,可以以逗号分割的方式继续往下加
type:处理这个请求的具体类,实现IHttpHandler接口
2. 实现IHttpHandler接口
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace ImgProtector.BLL { public class SiteImgProtector : IHttpHandler { IHttpHandler Members#region IHttpHandler Members 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); } } #endregion } }