开发日志:基于IHttpHandler接口功能的防盗链应用
建立URLHandler.cs文件,代码如下
using System.Web;
namespace BaseLibrary {
public class UrlHandler : IHttpHandler {
//指明该HttpHandler的实现类是否需要缓存
public bool IsReusable {
get { return true; }
}
public UrlHandler() {
}
public void ProcessRequest(HttpContext context) {
string FileName = context.Server.MapPath(context.Request.FilePath);
if (context.Request.UrlReferrer != null) {
if (context.Request.UrlReferrer.Host == null) {
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg"); //被替换图片
} else {
if (context.Request.UrlReferrer.Host.IndexOf("vote.yeshj.com") > -1) //这里是你的域名,如www.maticsoft.com
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
} else {
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg");
}
}
} else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}
}
}
}
namespace BaseLibrary {
public class UrlHandler : IHttpHandler {
//指明该HttpHandler的实现类是否需要缓存
public bool IsReusable {
get { return true; }
}
public UrlHandler() {
}
public void ProcessRequest(HttpContext context) {
string FileName = context.Server.MapPath(context.Request.FilePath);
if (context.Request.UrlReferrer != null) {
if (context.Request.UrlReferrer.Host == null) {
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg"); //被替换图片
} else {
if (context.Request.UrlReferrer.Host.IndexOf("vote.yeshj.com") > -1) //这里是你的域名,如www.maticsoft.com
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
} else {
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg");
}
}
} else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}
}
}
}
在网站的Web.config中的<httpHandlers></httpHandlers>节点中添加如下代码:
<httpHandlers>
<add verb="*" path="*.jpg" type="BaseLibrary.UrlHandler, BaseLibrary"/>
</httpHandlers>
<add verb="*" path="*.jpg" type="BaseLibrary.UrlHandler, BaseLibrary"/>
</httpHandlers>
配置网站的IIS
在站点的主目录=》配置=》ISAPI中
添加一个扩展名为“.jpg”;
可执行文件地址为:“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”的扩展
这样,在外展链接本周图片时,就会显示no.jpg
思考:
这样做只是做了.jpg的防盗链,如何做多种图片格式的防盗链?