在Global全局文件中的Application_BeginRequest示例


只要有人訪問本網(wǎng)站,都要執(zhí)行全局文件的Application_BeginRequest事件。因此我們可以防盜鏈。

示例要求:凡不是網(wǎng)站本機(jī)登錄的都給客戶端提示,用圖片顯示。

分析:由于網(wǎng)頁在加載時不是一次性全部加載,如先加載網(wǎng)頁,再加載相關(guān)的js文件,再加載圖片等,因此在客戶端上有個圖片元素,在此事件中判斷請求的類型是否為圖片并且是否是以localhost登錄的,如果不是就發(fā)送客戶端的另個圖片。

開發(fā)步驟:

   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文件,寫入以下內(nèi)容




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.運(yùn)行網(wǎng)頁,用loaclhost顯示為pic.jpg文件,如果在地址欄中改為127.0.0.1則會顯示我們要的forbid.png文件


原文鏈接:在Global全局文件中的Application_BeginRequest防盜鏈