您的位置:首页 > 编程语言 > ASP

[译] 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 事件
[根据 Adam Freeman – Pro ASP.NET MVC 5 Platform 选译]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: