在Global全局文件中的Application_BeginRequest示例


只要有人访问本网站,都要执行全局文件的Application_BeginRequest事件。因此我们可以防盗链。

示例要求:凡不是网站本机登录的都给客户端提示,用图片显示。

分析:由于网页在加载时不是一次性全部加载,如先加载网页,再加载相关的js文件,再加载图片等,因此在客户端上有个图片元素,在此事件中判断请求的类型是否为图片并且是否是以localhost登录的,如果不是就发送客户端的另个图片。

开发步骤:

   1.在目录中放两个图片,一个图片为正常显示,另一个为禁用提示的图片

   2.新建一HTML页面,它的源码为:


1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3<head>
4    <title></title>
5</head>
6<body>
7    <img src="imgs/pic.jpg" />
8</body>
9</html>
 3.添加Global.asax文件,写入以下内容




01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.Security;
06using System.Web.SessionState;
07 
08namespace GlobalTest
09{
10    public class Global : System.Web.HttpApplication
11    {
12 
13        protected void Application_Start(object sender, EventArgs e)
14        {
15 
16        }
17 
18        protected void Session_Start(object sender, EventArgs e)
19        {
20 
21        }
22 
23        protected void Application_BeginRequest(object sender, EventArgs e)
24        {
25           if(HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg")&&HttpContext.Current.Request.UrlReferrer.Host!="localhost")
26           {
27               HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/imgs/forbid.png"));
28               HttpContext.Current.Response.End();
29           }
30 
31        }
32 
33        protected void Application_AuthenticateRequest(object sender, EventArgs e)
34        {
35 
36        }
37 
38        protected void Application_Error(object sender, EventArgs e)
39        {
40 
41        }
42 
43        protected void Session_End(object sender, EventArgs e)
44        {
45 
46        }
47 
48        protected void Application_End(object sender, EventArgs e)
49        {
50 
51        }
52    }
53}
4.运行网页,用loaclhost显示为pic.jpg文件,如果在地址栏中改为127.0.0.1则会显示我们要的forbid.png文件


原文链接:在Global全局文件中的Application_BeginRequest防盗链