[译] ASP.NET 生命周期 – ASP.NET 请求生命周期(四)
2016-02-03 09:43
603 查看
不使用特殊方法来处理请求生命周期事件
HttpApplication 类是全局应用类的基类,定义了可以直接使用的一般 C# 事件。那么使用标准 C# 事件还是特殊方法那就是个人偏好的问题了,如果喜欢,也可以将这两种方式混合起来使用。using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace SimpleApp { public class MvcApplication : System.Web.HttpApplication { public MvcApplication() { BeginRequest += RecordEvent; AuthenticateRequest += RecordEvent; PostAuthenticateRequest += RecordEvent; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } private void RecordEvent(object src, EventArgs args) { List<string> eventList = Application["events"] as List<string>; if (eventList == null) { Application["events"] = eventList = new List<string>(); } string name = Context.CurrentNotification.ToString(); if (Context.IsPostNotification) { name = "Post" + name; } eventList.Add(name); } } }
View Code
我改变了 RecordEvent 方法的签名,因此采用了标准的事件处理器签名:一个对象代表的是事件的源,EventArgs 对象描述的就是事件。我没有使用这两个参数提供的值,相反,我使用了 Context.CurrentNotification 属性和 Context.IsPostNotification 属性提供的相关信息。
我不明白微软为什么以这样的一个方式来实现事件,但是如果你不想使用特殊方法或者 lambda 表达式的话,那你就必须使用这种方式。注意到,在上面的代码中,我在 Context.CurrentNotification 属性上使用了 ToString 方法,这是必须的,因为 CurrentNotification 属性返回的是一个 System.Web.RequestNotification 枚举值。详见下表:
表 1 – RequestNotification 枚举值
值 | 描述 |
BeginRequest | 对应到 BeginRequest 事件 |
AuthenticateRequest | 对应到 AuthenticateRequest 和 PostAuthenticateRequest 事件 |
AuthorizeRequest | 对应到 AuthorizeRequest 事件 |
ResolveRequestCache | 对应到 ResolveRequestCache 和 PostResolveRequestCache 事件 |
MapRequestHandler | 对应到 MapRequestHandler和 PostMapRequestHandler 事件 |
AcquireRequestState | 对应到 AcquireRequestState 和 PostRequestState 事件 |
PreExecuteRequestHandler | 对应到 PreExecuteRequestHandler 事件 |
ExecuteRequestHandler | 对应到 ExecuteRequestHandler 事件 |
ReleaseRequestState | 对应到 ReleaseRequestState 和 PostReleaseRequestState 事件 |
UpdateRequestCache | 对应到 UpdateRequestCahce 事件 |
LogRequest | 对应到 LogRequest 事件 |
EndRequest | 对应到 EndRequest 事件 |
SendResponse | 指示响应正在被发送——不完全对应到 PreSendRequestHeaders 和 PreSendRequestContent 事件 |
相关文章推荐
- 个人笔记 asp 10 asp随机数
- Raspbian 2019-06-20 发布,基于即将发布的Debian 10
- raspberrypi监控室内温度
- 个人笔记 asp 09 asp字符串转换
- 个人笔记 asp 08 asp设置保留小数点后两位
- 个人笔记 asp 07 替换函数
- 个人笔记 asp 06 asp重定向页面
- 个人笔记 asp 05 asp清除session
- ASP.NET中FORM验证中的cookieless属性
- 【ASP.NET Identity系列教程(一)】ASP.NET Identity入门
- Spring AspectJ AOP 示例
- c#的aspx页面中引用了用户控件,如何相互调用后台方法
- asp+ajax版的购物车
- andrid 上传图片 asp.net 后台接收并保存
- ASP.NET 使用 System.Web.Script.Serialization 解析 JSON (转)
- ASP.NET 系列:单元测试之ConfigurationManager
- 树莓派:VNC远程登录Raspbian图形界面(tightvncserver)
- ASP.NET MVC中使用异步控制器
- 利用程序将.jrxml导出为.jasper文件并用PDF显示(2)
- ajax success 没进入后台 返回login.aspx的html