怎么在asp.net2.0中使用Global.asax


Global.asax in Visual Studio 2005

In Visual Studio 2003, the Global.asax consisted of two files: Global.asax (design-time HTML) and Global.asax.xx (language-specific code-behind). The class was also named Global by default and could be referenced accordingly througout the application. Since Global.asax was an incarnation of HttpApplication at runtime, I added application-level properties and methods to the Global class.
 
The Global.asax in Visual Studio 2005, however, is much different by default. When adding a new 'Global Application Class' to your project, you'll get the Global.asax, but no code-behind. This really isn't a big deal because VS2005 has IntelliSense in the design-time HTML files now, but there are still differences. I want to describe some of those differences here for those that are used to Global.asax circa VS2002/2003.

Designer View

Global.asax seems to no longer have a designer view. With this view, you could drag items from Server Explorer, such as Event Log, into your project. I never really used this feature, so that's all I've got to say about that.

Importing Namespaces

I began coding Global.asax as I had always done in Global.asax.cs (C# is my language of choice), but the using statement for importing namespaces caused a compile error. Instead you have to use the @Import directive:
 
<%@ Import Namespace="System.Workflow.Runtime" %>
 
//这条加进去会出错,不知道是不是版本不同,可能这篇文章有点老

Global Class Name

I suppose Global.asax would get compiled into an anonymously named class, but I could not find a class reference that contained the properties/methods I had coded. At this point, I began searching for a better solution to my need for a Global class.
 
My first solution was to create a new class, Global.asax.cs (in the App_Code folder). I then made this file the code-behind for Global.asax with the CodeBehind attribute of the @Application directive:
 
<%@ Application Language="C#" CodeBehind="Global.asax.cs" %>
 
This worked out ok, but something still didn't feel right. The Global class (in Global.asax.cs) inherits System.Object, but the Global.asax still functioned as an instance of HttpApplication because code in Application_Start and Application_End would run accordingly.
 
My second and final attempt normalized the class hierarchy between these two files. In Global.asax.cs, I changed the Global class to inherit HttpApplication. I then replaced the CodeBehind attribute of the @Application directive in Global.asax with the Inherits attribute:
 
<%@ Application Language="C#" Inherits="Global" %>
//CodeBehind="Global.asax.cs" 和 Inherits="Global"要放到一起
 
Now the class hierarchy matched the usage and I had the familiar Global class to program against.

posted @ Monday, November 14, 2005 6:10 AM 

原文地址:https://www.cnblogs.com/lsjwzh/p/1087623.html