ASP.NET网站使用HttpHandler实现图片防盗链功能
网站的图片给盗链是不是觉得很头痛呢?下面方法使用.NET的HttpHandler来实现图片防盗链.
第一步:创建文件 CustomHandler.cs,代码如下:
using System;
using System.Web;
namespace CustomHandler{
public class JpgHandler : IHttpHandler{
public void ProcessRequest(HttpContext context){
// 获取文件服务器端物理路径
string FileName = context.Server.MapPath(context.Request.FilePath);
// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host == null){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}else{
// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}
public bool IsReusable{
get{ return true; }
}
}
}
第二步 编译这个文件(这个文件也可以直接在项目生成发布,就不会运行下面命令了)
csc /t:library /r:System.Web.dll CustomHandler.cs
第三步 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。
第四步 在Web.Config 中注册这个Handler。
<system.web>
<httpHandlers>
<add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
</httpHandlers>
</system.web>
第五步:在IIS配置(如下图)
上图可执行文件路径为:
c:windowsmicrosoft.netframeworkv2.0.50727aspnet_isapi.dll