第一步:添加类 myhandler.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// myhandler 的摘要说明
///
public class myhandler:IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string FileName = context.Server.MapPath(context.Request.FilePath);
string host = context.Request.UrlReferrer.Host;
if (context.Request.UrlReferrer.Host == null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/error.gif");//被替换图片
}
else
{
if (host.IndexOf("xh100.com") > -1 || host.IndexOf("baidu.com") > -1 || host.IndexOf("bing.com") > -1 || host.IndexOf("google.com") > -1 || host.IndexOf("sogou.com") > -1 || host.IndexOf("360.cn") > -1)//这里是你的域名
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/error.gif");
}
}
}
public bool IsReusable
{
get { return true; }
}
public myhandler()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
第二步: Web.config 的 中间 添加
< httpHandlers > < add type="myhandler,App_Code" path="*.jpg" verb="*" />< add type="myhandler,App_Code" path="*.gif" verb="*" />< /httpHandlers >
第三步:IIS 中 选择网站->右键点击属性->点击虚拟目录->配置->映射->添加
可执行文件选择:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll
扩展名 .jpg
gif的图片也类似添加防止盗链
服务器带宽被占,网站的访问量也不大,一直找不到原因。后来才想起网站图片被别人大量盗链。哎,没足够的银子想弄图片网站真不行。