`
lovnet
  • 浏览: 6694056 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

HttpApplication Class and the ASP.NET Application Object

阅读更多

http://www.eggheadcafe.com/articles/20030211.asp

HttpApplication Class and the ASP.NET Application Object
By Peter A. Bromberg, Ph.D.
Printer - Friendly Version


The ASP.NET HttpApplication class hides a number of complex concepts in order to simplify the programming model. Some of these simplifications are designed to handle compatibility issues with the classic Microsoft Active Server Pages (ASP) Application object in order to make migration easier. Therefore, it may be important for developers to understand some of the differences, in particular where performance issues are a concern.

HttpApplication Class and the
ASP.NET Application Object
By Peter A. Bromberg, Ph.D.
Printer - Friendly Version
Peter Bromberg

HttpApplication Class and the
ASP.NET Application Object
By Peter A. Bromberg, Ph.D.
Printer - Friendly Version
Peter Bromberg

The ASP.NET HttpApplication class hides a number of complex concepts in order to simplify the programming model. Some of these simplifications are designed to handle compatibility issues with the classic Microsoft Active Server Pages (ASP) Application object in order to make migration easier. Therefore, it may be important for developers to understand some of the differences, in particular where performance issues are a concern.

Application Class and Application Instances

An application class is defined in the Global.asax file. The code in Global.asax defines a new class that is derived from System.Web.HttpApplication. Consider the following code in Global.asax, which adds a new object array to the Application object:

 public class Global : System.Web.HttpApplication
       {
        public Global()
           {
		   InitializeComponent();
           }
protected void Application_Start(Object sender, EventArgs e) { this.Application.Add("TestItem",new object[]{"one","two","three"}); }

And here, in the Page_Load event handler of a page in our Application , we will pull it back out:



private void Page_Load(object sender, System.EventArgs e)
{
object[] MyStuff=(object[])Page.Application["TestItem"];
for(int i=0;i<MyStuff.Length;i++)
Response.Write(MyStuff[i]+" <br/>");
}

In the absence of a Global.asax file, the base class, HttpApplication, is used as the application class.

The ASP.NET runtime creates as many instances of application classes as needed to process requests simultaneously. For most applications, this number is limited to the number of threads and remains in the range of 1 through 100, depending on the hardware, server load, configuration, and so on. Many requests reuse application instances, and a list of free application instances is kept during periods of reduced load. Application instances are used in a thread-safe manner, that is, one request at a time. This has important implications:

  • You do not have to worry about locking when you access non-static members of the application class.
  • Application code can store request data for each request in non-static members of the application class (except after the EndRequest event because this event can maintain the request for a long time).

Because static members of any class, including an application class, are not thread-safe, the user code must provide appropriate locking for access to static members. This applies to any static member that you add to the application class.

Microsoft provides the following guidelines to access the application instance that is associated with the current request:

  • From the Global.asax, use the this (Me in VB.Net) object.
  • From a page, every page includes a strongly-typed ApplicationInstance property (e.g., "Page.Application["TestItem"]")
  • From the HttpContext object, use the HttpContext.ApplicationInstance property (which you type as HttpApplication):
HttpApplication ctx=(HttpApplication)HttpContext.Current.ApplicationInstance;
     object[] MyAppStuff=(object[])ctx.Application["TestItem"];
     for(int j=0;j<MyAppStuff.Length;j++)
Response.Write(MyAppStuff[j]+"<BR/>");

Because Application refers to the global application state dictionary in classic ASP, ASP.NET uses ApplicationInstance and not Application as a property name to refer to the application instance that processes the current request.

Application Events

The lifetime of a request (commonly referred to as the "Http pipeline") consists of a series of the application events (and some implicit steps that ASP.NET implements). These events are listed below in the order in which they are executed:

1. BeginRequest

2. AuthenticateRequest event

3. DefaultAuthentication internal event

4. AuthorizeRequest event

5. ResolveRequestCache event

6. Internal step to "map handler" (when compilation takes place, a page instance is created)

7. AcquireRequestState event

8. PreRequestHandlerExecute event

9. Internal step to "execute handler" (when the page code is executed)

10. PostRequestHandlerExecute event

11. ReleaseRequestState event

12. Internal step to filter responsesUpdateRequestCache event

13. UpdateRequestCache event

14. EndRequest event

The following items can handle these events:

  • Internal ASP.NET page framework (for example, steps 6, 9, and 12 in the preceding list).
  • HTTP modules that are configured for the application. The default list of HTTP modules is defined in the Machine.config file. Additional custom modules may be specified by the developer in the web.config for the application.
  • Code in Global.asax that is hooked through the Application_[On]EventName method or that is hooked explicitly when you add event handlers for an alternative handler name:

	  protected void Application_OnBeginRequest(Object sender, EventArgs e)
              {
               Response.Write("OnBeginRequest Fired!");
              }

Each event can have synchronous and asynchronous subscribers. Asynchronous subscribers are executed first. Not all events are always executed; the only event that is always executed is EndRequest. As a result, you should perform all after-request cleanup in the EndRequest event:


	  protected void Application_OnEndRequest(Object sender, EventArgs e)
{ Response.Write("OnEndRequest Fired!<br/>"); }


In most cases, the actual response content is sent to the client after the application instance is finished with the response (which is after EndRequest).

Application_OnStart and Application_OnEnd

ASP.NET introduces the Application_OnStart and Application_OnEnd "events" for compatibility with classic ASP. These handlers are executed only once in the lifetime of an application and not for every application instance. So, if you change non-static members in these methods, you affect only one application instance and not all instances. You can initialize one application instance either in the constructor or by overriding the Init method.

Application_OnStart is a logical equivalent to the class constructor for the application class, but it offers one advantage: the code has access to the HttpContext for the first request to the application.

Application State

Application state is a global dictionary of late-bound objects, which classic ASP introduces to compensate for the absence of global variables in Microsoft Visual Basic Scripting Edition (VBScript). In ASP.NET, you can access application state through one of the following:

  • Application property (which is defined in both HttpApplication and Page classes)
  • HttpContext.Application

ASP.NET includes application state primarily for compatibility with classic ASP so that it is easier to migrate existing applications to ASP.NET. It is recommended that you store data in static members of the application class instead of in the Application object. This increases performance because you can access a static variable faster than you can access an item in the Application dictionary.

To access static application members from pages in Microsoft Visual C# .NET and Microsoft Visual Basic .NET, you must use the ClassName attribute in Global.asax to name your application class. For example, in a "Script Only" global.asax:

<%@ Application Language="C# | VB" ClassName="MyClass" %>

In CodeBehind:

public class Global : System.Web.HttpApplication

{

public static string StaticTest ="This is the original value";
. . .

If a static member is named MyStaticMember in your Global.asax file, you can use MyClass.MyStaticMember to access it from your page.

The code in the sample Web application for this article writes items to the output stream that illustrate some of these unique properties as they are set or fired from within the global.asax or the Page itself, and will make it easier to examine and / or experiment with the unique Application Object.

Download the Code that accompanies this article

分享到:
评论

相关推荐

    Inside ASP.NET

    The HttpApplicationState Class (Application Intrinsic Object) The HttpSessionState Class ( Session Intrinsic Object) The HttpRequest Class (Request Intrinsic Object) The HttpResponse Class ...

    ASP.NET的网页代码模型及生命周期

    q designer.cs页文件:用来为页面的控件做初始化工作,一般只有ASP.NET应用程序(Web Application)才有。 ASP.NET页面中包含两种代码模型,一种是单文件页模型,另一种是代码隐藏页模型。这两个模型的功能完全一样...

    从底层了解ASP.NET体系结构

    ASP.NET是什么?  2.从浏览器到ASP.NET  3.ISAPI连接  4.IIS5和IIS6的不同之处  5.进入.NET运行时  6.加载.NET—稍微有点神秘  7.回到运行时  8.HttpRuntime,HttpContext以及HttpApplication  9.Web程序的...

    ASP.NET Night Words

    第1章 asp.net介绍 2 1.1 xhtml语言 2 1.2 静态网页 3 1.3 动态网页 3 1.4 iis的安装和配置 3 1.5 asp.net开发的预备知识 4 1.5.1 asp.net简介 4 1.5.2 在iis上配置asp.net 4 1.5.3 visual studio版本与 ...

    ASP.NET的工作原理探索

    本文比较深入地讨论了ASP.NET程序的工作过程,解释了ASP.NET程序的加载原理。为动态网页设计和开发B/S模式的程序奠定基础

    Microsoft - Microsoft ASP.NET 4 Step by Step May 2010

    18 The HttpApplication Class and HTTP Modules .............. 385 19 HTTP Handlers......................................... 405 Part V Dynamic Data, XBAP, MVC, AJAX, and Silverlight 20 Dynamic Data ...

    ASP.NET体系结构

    Rick Strahl文章的翻译,讲了关于ASP.NET的底层的工作机制,内容包括:ISAPI连接;IIS5和IIS6的不同;HttpRuntime,HttpContext以及HttpApplication; Web程序的主要部分—HttpApplication;ASP.NET管道;HttpContext...

    Url重写篇视频------本讲将通过实例比较ASP.NET下的三种典型URL重写方案

    但是可以在 Michele Leroux Bustamante 的文章 Inside IIS and ASP.NET 中找到对此内容的深入讨论。ASP.NET 引擎仅处理那些扩展名已明确映射至 IIS 中的 aspnet_isapi.dll 的传入 Web 请求,了解这一点非常重要。 ...

    asp.net面试题

    四、关于ASP.NET中的代码隐藏文件的描述正确的是( )。 A.Web窗体页的程序的逻辑由代码组成,这些代码的创建用于与窗体交互。该文件称作为“代码隐藏”文件,如果用C#创建,该文件将具有“.ascx.cs”扩展名 B.web...

    SitemapAspNet:用于 ASP.NET MVC 的站点地图生成器

    用于 ASP.NET MVC 的站点地图生成器那是什么... 使用示例: public class MvcApplication : HttpApplication{ protected void Application_Start () { // Provides routes to class configuration generator sitemap.

    ASP.NET C#中Application的用法教程

    Application对象生存期和Web应用程序生存期一样长,生存期从Web应用程序网页被访问开始,HttpApplication类对象Application被自动创建,直到没有一个网页被访问时结束,Application对象被自动撤销。因此Application...

    Asp.net的应用程序对象和页面生存周期

    IIS在接到一个新的http请求后,最终会调用asp.net_isapi.dll的 ISAPI扩展(特指IIS6.0环境,iis7.0的应用程序...Application –&gt;相当于传统意义上asp时代的application对象,通常用于定义一个asp.net应用的全局变量 Cont

    Coderr.Client.AspNet:基于ASP.NET的应用程序(WebApi和MVC除外)的客户端库

    protected void Application_Start ( object sender , EventArgs e ) { // replace with your server URL and your appkey/SharedSecret. var uri = new Uri ( " https://report.coderr.io/ " ); Err . ...

    ASP.NET MVC3关于生成纯静态后如何不再走路由直接访问静态页面

    要解决这个问题,我们需要先了解ASP.NET应用程序的生命周期,先看下面作者整理的一张图片: 从图中我们可以清楚的看到:通用IIS访问应用程序时,每次的单个页面URL访问时,都会先经过HttpApplication 管线处理请求...

    解读ASP.NET 5 & MVC6系列教程(6):Middleware详解

    ASP.NET 5和之前版本的最大区别是对HTTP Pipeline的全新重写,在之前的版本中,请求过滤器的通常是以HttpModule为模块组件,这些组件针对HttpApplication里定义的各个周期内的事件进行响应,从而用于实现认证、全局...

    ASP.NET中常见文件类型、扩展名、存放位置及用途总结

    有关更多信息,请参见 ASP.NET 用户控件。 .ashx 应用程序根目录或子目录。 一般处理程序文件,该文件包含实现 IHttpHandler 接口以处理所有传入请求的代码。 有关更多信息,请参见 HTTP 处理程序介绍。 .asmx 应用...

    PosInformatique.AspNet.WebForms.DependencyInjection:PosInformatique.AspNet.WebForms.DependencyInjection是一个库,用于为Microsoft .Extensions.DependencyInjection添加ASP.NET Web窗体的IoC容器支持。

    在ASP .NET WebForms项目上添加程序包后,在后面的Global.asax.cs代码中的HttpApplication类的Application_Start中的以下行中,调用AddServiceCollection : public class Global : HttpApplication { protected ...

    剖析Asp.Net Web API路由系统—WebHost部署方式

    上一篇我们剖析了Asp.Net路由系统,今天我们再来简单剖析一下Asp.Net Web API以WebHost方式部署时,Asp.Net Web API的路由系统内部是怎样实现的。还是以一个简单实例开头。 创建一个空的WebApi项目,在Global中注册...

    asp.net计算每个页面执行时间的方法

    本文实例讲述了asp.net计算每个页面执行时间的方法。分享给大家供大家参考。具体分析如下: 这里的asp.net代码可实现计算每个页面的执行时间,无需要修改页面的相关代码,这段代码会给所有的页面统一加上执行时间...

    ASP.NET中的URL过滤实现代码

     namespace QTJZ { public class Filters : IHttpModule, IRequiresSessionState { public void Dispose() { } public void Init(HttpApplication application) { application.AcquireRequestSt

Global site tag (gtag.js) - Google Analytics