asp.net中利用ashx實現圖片防盜鏈的原理分析
更新時間:2008年09月10日 00:59:19 作者:
盜鏈的危害我就不說了,網上有很多。下面是asp.net下利用ashx的防盜鏈原理分析
直接分析盜鏈原理:看下面用httpwatch截獲的http發(fā)送的數據
GET /Img.ashx?img=svn_work.gif HTTP/1.1
Accept: */*
Referer: http://chabaoo.cn/
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; CIBA)
Host: chabaoo.cn
Connection: Keep-Alive
該數據包表示請求http://chabaoo.cn/Img.ashx?img=svn_work.gif文件。我們可以看到Referer表示上一頁請求頁面地址,也就是文件來源。Host表示當前請求的主機地址。
下面是一個盜鏈的數據包
GET /Img.ashx?img=svn_work.gif HTTP/1.1
Accept: */*
Referer: http://745.cc/
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; CIBA)
Host: chabaoo.cn
Connection: Keep-Alive
我們可以看到,上面兩個數據,表示對于同一個文件:http://chabaoo.cn/Img.ashx?img=svn_work.gif的請求過程,這里的不同就是Referer,也就是都是請求同一個文件,但是請求的來源是不同的。因此我們可以在程序里判斷是否是來源于當前服務器,來判斷是否是盜鏈。明白原理以后,實現防盜鏈就非常簡單了。下面以圖片防盜鏈來實現一個演示。ASP.NET中添加一個img.ashx文件,然后后臺代碼如下:
復制代碼 代碼如下:
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
namespace GetImage
{
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Img : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
if (context.Request.UrlReferrer != null && context.Request.UrlReferrer.Host.Equals(context.Request.Url.Host, StringComparison.InvariantCultureIgnoreCase))
context.Response.WriteFile(context.Server.MapPath("~/" + context.Request.QueryString["img"]));
else
context.Response.WriteFile(context.Server.MapPath("~/logo.gif"));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
表示如果來源不為空,并且來源的服務器和當前服務器一致,那就表示是正常訪問,非盜鏈。正常訪問文件內容。
否則就是盜鏈,返回網站LOGO。
你甚至可以做成隨機返回正確的圖片,隨機返回錯誤圖片,或者定時返回正確圖片,定時返回錯誤圖片。
然后就是圖片的使用了,這時使用圖片就不是直接<input type="image" src="svn_work.gif" />了,而是<input type="image" src="/Img.ashx?img=svn_work.gif" />,就是說通過img,ashx來讀取圖片。別人盜鏈的話要用下面代碼:<input type="image" src="http://chabaoo.cn/Img.ashx?img=svn_work.gif" />。
趕緊給自己的網站加上防盜鏈吧!
相關文章
ASP.NET中TextBox使用Ajax控件顯示日期不全的問題解決方法
這篇文章介紹了ASP.NET中TextBox使用Ajax控件顯示日期不全的問題解決方法,有需要的朋友可以參考一下2013-10-10
Repeater的FooterTemplate顯示某列總計思路與代碼
在Repeater的FooterTemplate顯示某列總計,接下來與大家分享詳細的實現方案,感興趣的各位可以參考下哈2013-03-03
asp.net 中將表單提交到另一頁 Code-Behind(代碼和html在不同的頁面)
To send Server control values from a different Web Forms page2009-04-04
asp.net 使用Silverlight操作ASPNETDB數據庫
asp.net下使用Silverlight操作ASPNETDB數據庫的實現代碼2010-01-01

