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

Asp.net网站使用HttpHandler实现图片防盗链功能

2011-10-28 23:46 1026 查看
第一步:创建PicHandler.cs文件,代码如下:

using System.Web;

namespace MyHttpModule
{
public class PicHandler:IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string strFile = context.Server.MapPath(context.Request.FilePath);
if(context.Request.UrlReferrer==null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
else
{
if(context.Request.UrlReferrer.Host.IndexOf("youdomain.com")>-1)
{
context.Response.ContentType = "imae/jpeg";
context.Response.WriteFile(strFile);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}

/// <summary>
/// 获取一个值,该值指示其他请求是否可以使用IHttpHander实例。也就是后续的Http请求是不是可以继续使用实现了该接口的类的实例
/// </summary>
public bool IsReusable
{
get { return true; }
}
}
}

第二步:编译文件成DLL;

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

第三步:将编译妇的DLL拷贝到Bin目录下;

第四步:在Web.config中注册这个Handler;

<httpHandlers>
<add path="*.jpg" verb="*" type="MyHttpHandler.PicHandler,MyHttpHandler"/>
</httpHandlers>第五步:在IIS中配置应用程序扩展(jpg)

C:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: