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

IHttpHandler 轻松实现图片防盗链

2008-01-21 13:43 507 查看
VS2008,C#



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

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: