asp.net本质论——Global.asax

通过 global.asax 创建 HttpApplication 的事件处理程序
 
在 Visual Studio 中创建的普通网站项目中的 Global.asax 如下所示:
 
<%@ Application Language="C#" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e)
    {
    }
    void Application_End(object sender, EventArgs e)
      {
          //  在应用程序关闭时运行的代码
      }
      void Application_Error(object sender, EventArgs e)
      {
          // 在出现未处理的错误时运行的代码
      }
      void Session_Start(object sender, EventArgs e)
      {
          // 在新会话启动时运行的代码
      }
      void Session_End(object sender, EventArgs e)
      {
          // 在会话结束时运行的代码。
          // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
          // InProc 时,才会引发 Session_End 事件。如果会话模式设置为
          // StateServer 或 SQLServer,则不会引发该事件
      }
</script>
 
注意开始的指令 <%@ Application Language="C#" %>,表示下面的代码将被生成一个 HttpApplication 的派生类,这个类的名字固定为 global_asax。这个派生类由  ASP.NET 网站自动生成,如果希望看到生成的文件,那么,在调试模式下运行网站程序之后,在 .NET 的临时文件夹中可以找到生成的派生类的源码文件。如果使用开发服务器,那么在 Windows7 下应该在以下目录中:
 
C:\Users\用户名\AppData\Local\Temp\Temporary ASP.NET Files\项目名称\ 可以看到类似 App_global.asax.vhopxkyt.0.cs名称的代码文件。文件的主要内容如下:
 
#pragma checksum "E:\epress\chapter2-3-web\global.asax" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "3CD84B3DA089512A6A6F91AA3904CC46"
//---------------------------------------------------------------------------  
// <auto-generated> 
//    This code was generated by a tool.  
//    Runtime Version:4.0.30319.1  
//  
//    Changes to this file may cause incorrect behavior and will be lost if  
//    the code is regenerated.  
// </auto-generated> 
//---------------------------------------------------------------------------   

namespace ASP {
[System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
public class global_asax : global::System.Web.HttpApplication {
      private static bool @__initialized;
      #line 3 "E:\epress\chapter2-3-web\global.asax"
      这里将是原来 Global.asax 文件的内容
      #line default
      #line hidden
      [System.Diagnostics.DebuggerNonUserCodeAttribute()]
      public global_asax() {
          if ((global::ASP.global_asax.@__initialized == false)) {
              global::ASP.global_asax.@__initialized = true;
          }
      }
      protected System.Web.Profile.DefaultProfile Profile {
          get {
              return ((System.Web.Profile.DefaultProfile)(this.Context.Profile));
          }
      }
 
global.asax 中 HttpApplication 事件的自动注册
 
在 global.asax 中,针对 HttpApplication 的事件处理,可以通过定义特殊命名的方法来实现。首先,这些方法必须符合 System.EventHandler,因为所有的 HttpApplication 管道事件都使用这个委托定义。第二,方法的作用域必须是 public。第三,方法的命名格式必须如下:Application_注册的事件名称。按照这种命名方法定义在 global.asax中的方法将被自动注册到对应的事件中。
 
例如,希望在 global.asax 中注册 PostAuthenticateRequest 事件处理,那么在 global.asax 中应该定义一个如下的方法:
 
void Application_PostAuthenticateRequest(object sender, EventArgs e){
     // 具体的事件处理
}




posted @ 2012-12-22 04:28  Adming  阅读(388)  评论(0编辑  收藏  举报