Global中的事件执行顺序
The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks. Let's take a closer look at how you may use it in your application development efforts.
Overview
The Global.asax file is in the root application directory. While
Visual Studio .NET automatically inserts it in all new ASP.NET projects,
it's actually an optional file. It's okay to delete it--if you aren't
using it. The .asax file extension signals that it's an application file
rather than an ASP.NET file that uses aspx.
The Global.asax file is configured so that any direct HTTP request
(via URL) is rejected automatically, so users cannot download or view
its contents. The ASP.NET page framework recognizes automatically any
changes that are made to the Global.asax file. The framework reboots the
application, which includes closing all browser sessions, flushes all
state information, and restarts the application domain.
Programming
The Global.asax file, which is derived from the HttpApplication
class, maintains a pool of HttpApplication objects, and assigns them to
applications as needed. The Global.asax file contains the following
events:
- Application_Init: Fired when an application initializes or is
first called. It's invoked for all HttpApplication object instances. - Application_Disposed: Fired just before an application is
destroyed. This is the ideal location for cleaning up previously used
resources. - Application_Error: Fired when an unhandled exception is encountered within the application.
- Application_Start: Fired when the first instance of the
HttpApplication class is created. It allows you to create objects that
are accessible by all HttpApplication instances. - Application_End: Fired when the last instance of an
HttpApplication class is destroyed. It's fired only once during an
application's lifetime. - Application_BeginRequest: Fired when an application request is
received. It's the first event fired for a request, which is often a
page request (URL) that a user enters. - Application_EndRequest: The last event fired for an application request.
- Application_PreRequestHandlerExecute: Fired before the ASP.NET
page framework begins executing an event handler like a page or Web
service. - Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
- Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
- Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
- Application_AcquireRequestState: Fired when the ASP.NET page
framework gets the current state (Session state) related to the current
request. - Application_ReleaseRequestState: Fired when the ASP.NET page
framework completes execution of all event handlers. This results in all
state modules to save their current state data. - Application_ResolveRequestCache: Fired when the ASP.NET page
framework completes an authorization request. It allows caching modules
to serve the request from the cache, thus bypassing handler execution. - Application_UpdateRequestCache: Fired when the ASP.NET page
framework completes handler execution to allow caching modules to store
responses to be used to handle subsequent requests. - Application_AuthenticateRequest: Fired when the security module
has established the current user's identity as valid. At this point, the
user's credentials have been validated. - Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
- Session_Start: Fired when a new user visits the application Web site.
- Session_End: Fired when a user's session times out, ends, or they leave the application Web site.
The event list may seem daunting, but it can be useful in various circumstances.
Triggering
A key issue with taking advantage of the events is knowing the order
in which they're triggered. The Application_Init and Application_Start
events are fired once when the application is first started. Likewise,
the Application_Disposed and Application_End are only fired once when
the application terminates. In addition, the session-based events
(Session_Start and Session_End) are only used when users enter and leave
the site. The remaining events deal with application requests, and
they're triggered in the following order:
- Application_BeginRequest
- Application_AuthenticateRequest
- Application_AuthorizeRequest
- Application_ResolveRequestCache
- Application_AcquireRequestState
- Application_PreRequestHandlerExecute
- Application_PreSendRequestHeaders
- Application_PreSendRequestContent
- <<code is executed>>
- Application_PostRequestHandlerExecute
- Application_ReleaseRequestState
- Application_UpdateRequestCache
- Application_EndRequest
Applying to security
A common use of some of these events is security. The following C#
example demonstrates various Global.asax events with the
Application_Authenticate event used to facilitate forms-based
authentication via a cookie. In addition, the Application_Start event
populates an application variable, while Session_Start populates a
session variable. The Application_Error event displays a simple message
stating an error has occurred.
protected void Application_Start(Object sender, EventArgs e) {
Application["Title"] = "Builder.com Sample";
}
protected void Session_Start(Object sender, EventArgs e) {
Session["startValue"] = 0;
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie) {
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
} catch(Exception ex) {
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket) {
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned
// a pipe delimited string of role names.
string[2] roles
roles[0] = "One"
roles[1] = "Two"
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
protected void Application_Error(Object sender, EventArgs e) {
Response.Write("Error encountered.");
}
This example provides a peek at the usefulness of the
events contained in the Global.asax file; it's important to realize
that these events are related to the entire application. Consequently,
any methods placed in it are available through the application's code,
hence the Global name.
Here's the VB.NET equivalent of the previous code:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("Title") = "Builder.com Sample"
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("startValue") = 0
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
EventArgs)
' Extract the forms authentication cookie
Dim cookieName As String
cookieName = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie
authCookie = Context.Request.Cookies(cookieName)
If (authCookie Is Nothing) Then
' There is no authentication cookie.
Return
End If
Dim authTicket As FormsAuthenticationTicket
authTicket = Nothing
Try
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception
' Log exception details (omitted for simplicity)
Return
End Try
Dim roles(2) As String
roles(0) = "One"
roles(1) = "Two"
Dim id As FormsIdentity
id = New FormsIdentity(authTicket)
Dim principal As GenericPrincipal
principal = New GenericPrincipal(id, roles)
' Attach the new principal object to the current HttpContext object
Context.User = principal
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Response.Write("Error encountered.")
End Sub
A good resource
The Global.asax file is the central point for ASP.NET applications.
It provides numerous events to handle various application-wide tasks
such as user authentication, application start up, and dealing with user
sessions. You should be familiar with this optional file to build
robust ASP.NET-based applications.
我能在Global.asax文件中触发那些事件?
Application对象创建和结束时所触发的事件有
Application_Start
Application_End
Session对象创建和结束时所触发的事件有
• Session_Start
• Session_End
对程序有请求发生时触发的事件有 (按发生顺序排列)
• Application_BeginRequest
• Application_AuthenticateRequest
• Application_AuthorizeRequest
• Application_ResolveRequestCache
• Application_AcquireRequestState
• Application_PreRequestHandlerExecute
• Application_PostRequestHandlerExecute
• Application_ReleaseRequestState
• Application_UpdateRequestCache
• Application_EndRequest
当有程序有错误发生时触发的事件有
• Application_Error
• Application_Disposed
Global中的事件执行顺序的更多相关文章
- jquery中各个事件执行顺序如下:
jquery中各个事件执行顺序如下: 1.ajaxStart(全局事件) 2.beforeSend 3.ajaxSend(全局事件) 4.success 5.ajaxSuccess(全局事件) 6.e ...
- jquery ajax 中各个事件执行顺序
jquery ajax 中各个事件执行顺序如下: 1.ajaxStart(全局事件) 2.beforeSend 3.ajaxSend(全局事件) 4.success 5.ajaxSuccess(全局事 ...
- jquery ajax中各个事件执行顺序如下
$(function(){ setTimeout(function(){ $.ajax({ url:'/php/selectStudent.php', }); },0); $(document).aj ...
- jquery ajax 事件执行顺序
jquery中各个事件执行顺序如下: 1.ajaxStart(全局事件) 2.beforeSend 3.ajaxSend(全局事件) 4.success 5.ajaxSuccess(全局事件) 6.e ...
- jquery ajax事件执行顺序
jquery中各个事件执行顺序如下: 1.ajaxStart(全局事件) 2.beforeSend 3.ajaxSend(全局事件) 4.success 5.ajaxSuccess(全局事件) 6.e ...
- Unity3D中脚本的执行顺序和编译顺序
http://www.cnblogs.com/champ/p/execorder.html 在Unity中可以同时创建很多脚本,并且可以分别绑定到不同的游戏对象上,它们各自都在自己的生命周期中运行.与 ...
- ASP.NET Page对象各事件执行顺序(转)
很久没写 asp.net 的东西了,search 了一下 page 的事件执行顺序,找到如下的东西,仅仅做记录用 Page.PreInit 在页初始化开始时发生 Page.Init 当服务器控件初始化 ...
- 【转】Unity3D中脚本的执行顺序和编译顺序(vs工程引用关系)
http://www.cnblogs.com/champ/p/execorder.html 在Unity中可以同时创建很多脚本,并且可以分别绑定到不同的游戏对象上,它们各自都在自己的生命周期中运行.与 ...
- Web高级 Eventloop和事件执行顺序
1. EventLoop 1.1 调用栈 当一个方法执行时内部调用另外的方法,则会形成调用栈,如图: 1.2 任务队列 JavaScript有一个主线程执行当前任务,主线程的代码同步执行,并把遇到的事 ...
随机推荐
- 다음에 적용될 Auto_increment 값 알아 내기 (计算下一个Auto_increment的值)
Mysql 4.X <------ SHOW TABLE STATUS FROM [DB_NAME] LIKE '[TABLE_NAME]'; Mysql 5.X ----------- ...
- 用友NC V6.3打造集团企业高效信息平台
近年来,随着互联网快速发展,信息化管理的应用也越来越普及,信息化建设已经深入到很多企业的核心业务,而且为了确保业务稳定.可靠并快速.有效地 开展,企业经常会运用多个信息系统进行辅助支撑,但是,许多企业 ...
- C#学习笔记14:面向对象继承的特点和里氏转换
面向对象: 继承:减少代码. 单根性 传递性 子类没有从父类那里继承了构造函数,只是会默认的调用父类那个无参数的构造函数 Class person { Public String Name { Ge ...
- poj1274 匈牙利算法 二分图最大匹配
poj1274 题意: 有n个奶牛, m个畜舍, 每个畜舍最多装1头牛,每只奶牛只有在自己喜欢的畜舍里才能产奶. 求最大产奶量. 分析: 其实题意很明显, 二分图的最大匹配, 匈牙利算法. #incl ...
- linux添加用户、用户组、权限
# useradd –d /usr/sam -m sam 此命令创建了一个用户sam,其中-d和-m选项用来为登录名sam产生一个主目录/usr/sam(/usr为默认的用户主目录所在的父目录). 假 ...
- android开发 锁屏 真正的锁屏,是go锁屏那种。
想做个锁屏界面很久了,最近一周,历经千辛万苦,越过种种挫折,终于完美实现了这一要求,在此将锁屏思路分享出来. 注意:这不是什么一键锁屏,是类似“go锁屏”那样的锁屏界面. 准备:本程序共需要 两个ac ...
- Android logcat使用
Android logcat使用 1. Android日志说明 当Android系统运行的时候,会搜集所有的系统信息. logcat是Android系统的一个命令行工具,主要用来查看和过滤日志信息. ...
- lua package path 设置方法
lua package path 设置方法: 添加环境变量LUA_PATH="/add_path/?.lua;;" 1.add_path为新添加的目录: 2.一定要添加双引号: 3 ...
- cocos2dx 初探 - VS2012 HELLOWORLD
最近决定用cocos2dx 来做些试验性的东西,先装了个vs2012 再从网上下了cocos2dx-2.1.4就开工了. 仅是Windows 桌面调试还是很简单的. 上面三个项目源: Hellocpp ...
- 计算序列中第k小的数
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4046399.html 使用分治算法,首先选择随机选择轴值pivot,并使的序列中比pivot ...