Asp.Net 2.0 的App_Code目录中存储的源代码,在运行时将会自动进行编译,并且和Bin目录一样任意地方的其他代码(如页代码)会自动引用该目录。借由App_Code目录,我们可以很方便的创建各种全局代码段,并且比Global.asax来得灵活。
比如我有一个读取Cookie的函数很多页面都要用到,就可以在App_Code下建立一个类,假设叫MyGlobal。
1
public class MyGlobal
2
{
3
public static int ReadUidCookie()
4
{
5
if(HttpContext.Current.Request.Cookies["UserID"] != null)
6
{
7
HttpCookie userIDCookie = HttpContext.Current.Request.Cookies["UserID"];
8
int uid = Convert.ToInt32(userIDCookie.Value);
9
return uid;
10
}
11
return -1;
12
}
13
}

2

3

4

5

6

7

8

9

10

11

12

13

注意这里读取Cookie是用的 HttpContext.Current.Request.Cookies ,HttpContext.Current 用来取得调用这个函数那一页的Page类。在需要读Cookie的地方就可以用 MyGlobal.ReadUidCookie() 静态方法了。当然,这个类中也可以有变量,只要建立一个MyGlobal的实例,它里面的变量就可以当全局变量了。