///stopImage 的摘要说明
/// </summary>
public class stopImage:IHttpHandler
{
public stopImage()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (context.Request.UrlReferrer != null)
{
context.Response.Expires = 0;
context.Response.Clear();
context.Response.ContentType = "image/jpg";
context.Response.WriteFile(context.Request.PhysicalPath);
context.Response.End();
}
else
{
context.Response.Expires = 0;
context.Response.Clear();
context.Response.ContentType = "text/html";
context.Response.Write("盗链");
context.Response.End();
}
}
#endregion
}
需要配置一下webconfig,在System.Web下配置:
代码
<add verb="*" path="images/*.jpg" type="stopImage,App_Code"/>
上面的方式并不能防止迅雷等下载软件的下载,在迅雷里面输入这些地址照样可以下载。如果别的站引用了你的某个.zip的文件链接,这样还是可以直接下载到的。那该如何解决呢?我目前想到的就是加入session验证。
如果用户访问了你的下载页面则在load里面设置session[“visited”]=”true”,然后在下载里面增加一个session验证,代码如下(注意,需要继承
System.Web.SessionState.IRequiresSessionState才能使用session):
代码
if (null != context.Request.UrlReferrer && context.Session["visited"] == "true")
{
context.Response.Expires = 0;
context.Response.Clear();
context.Response.ContentType = "image/jpg";
context.Response.WriteFile(context.Request.PhysicalPath);
context.Response.End();
}
else
{
context.Response.Expires = 0;
context.Response.Clear();
context.Response.ContentType = "image/jpg";
context.Response.WriteFile(context.Request.PhysicalApplicationPath + "Images/error.jpg");
context.Response.End();
}
这样我们调试的时候调用迅雷下载这个图片就可以发现session里面是没有值的,当然就下载error图片了。
详细出处参考: http://www.jb51.net/article/26174.htm