在ASP.NET中使用Global.asax文件__教程 |
|
日期:2007-5-20 0:39:21 人气:74 [大 中 小] |
|
|
|
·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."); } 这个例子只是很简单地使用了一些Global.asax 文件中的事件;重要的是要意识到这些事件是与整个应用程序相关的。这样,所有放在其中的方法都会通过应用程序的代码被提供,这就是它的名字为Global 的原因。 这里是前面的例子相应的 VB.NET 代码: Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) |
|
出处:本站原创 作者:佚名 |
|
|