正 文

使用ASP.NET Global.asax 文件


www.7dspace.com  更新日期:2005-12-4 5:21:15  七度空间


使用这些事件的一个关键问题是知道它们被触发的顺序。Application_Init 和Application_Start 事件在应用程序第一次启动时被触发一次。相似地,Application_Disposed 和 Application_End 事件在应用程序终止时被触发一次。此外,基于会话的事件(Session_Start 和 Session_End)只在用户进入和离开站点时被使用。其余的事件则处理应用程序请求,这些事件被触发的顺序是:

· Application_BeginRequest

· Application_AuthenticateRequest

· Application_AuthorizeRequest

· Application_ResolveRequestCache

· Application_AcquireRequestState

· Application_PreRequestHandlerExecute

· Application_PreSendRequestHeaders

· Application_PreSendRequestContent

· <<执行代码>>

· Application_PostRequestHandlerExecute

· Application_ReleaseRequestState

· Application_UpdateRequestCache

· Application_EndRequest

这些事件常被用于安全性方面。下面这个 C# 的例子演示了不同的Global.asax 事件,该例使用Application_Authenticate 事件来完成通过 cookie 的基于表单(form)的身份验证。此外,Application_Start 事件填充一个应用程序变量,而Session_Start 填充一个会话变量。Application_Error 事件显示一个简单的消息用以说明发生的错误。

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.");
}

3页,页码:[1] [2] [3] 

上一篇:导出模板:未完的内容
下一篇:使用ADO.NET 和C# 处理BLOB 数据
作者:Tony Patton  来源:开发者在线 ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐