只要有人訪問本網站,都要執行全局文件的Application_BeginRequest事件。因此我們可以防盜鏈。
示例要求:凡不是網站本機登錄的都給客戶端提示,用圖片顯示。
分析:由於網頁在加載時不是一次性全部加載,如先加載網頁,再加載相關的js文件,再加載圖片等,因此在客戶端上有個圖片元素,在此事件中判斷請求的類型是否為圖片並且是否是以localhost登錄的,如果不是就發送客戶端的另個圖片。
開發步驟:
1.在目錄中放兩個圖片,一個圖片為正常顯示,另一個為禁用提示的圖片
2.新建一HTML頁面,它的源碼為:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <img src="imgs/pic.jpg" /> </body> </html>
3.添加Global.asax文件,寫入以下內容
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace GlobalTest { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { if(HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg")&&HttpContext.Current.Request.UrlReferrer.Host!="localhost") { HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/imgs/forbid.png")); HttpContext.Current.Response.End(); } } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
4.運行網頁,用loaclhost顯示為pic.jpg文件,如果在地址欄中改為127.0.0.1則會顯示我們要的forbid.png文件,如下圖