ASP.NET MVC学前篇之请求流程
对于请求的流程,文章的重点是讲HttpApplication和HttpModule之间的关系,以及一个简单的示例实现。(HttpModule又是MVC框架的入口点)
图1
在请求到达Web服务器过后进入ASP.NET的时候是通过ASP.NET来构造出一个HttpWorkerRequest对象,HttpWorkerRequest是抽象类类型,表示着一些请求处理的信息,然后由ASP.NET中的HttpRuntime类型来调用静态函数Proce***equest(),参数类型为HttpWorkerRequest,因为HttpWorkerRequest是抽象的,在使用的时候应该是系统内部会有个实现类。 在Proce***equest()方法的内部产生HttpApplication对象,这之间的过程,已经把HttpWorkerPequest对象处理后转变到HttpRequest对象,HttpRequest对象是公开的可代码访问的(图中没有表示出来)。 这个时候还没有执行HttpHandler程序,而是先执行HttpModule中的内容,它们订阅了HttpApplication中的事件用于在请求的各种状态之间做一下自定义的修改(这些在下面的示例中会说到。 然后执行HttpHandler,在处理程序执行完毕后,不是到HttpResponse,而是又到了HttpModule中执行请求完成后的一些自定义操作,这是在HttpApplication中约定好的,在这些都完成的情况下才会做Response操作。
我们将在下面的示例中模拟的演示一下在HttpApplication类型中的事件使用模型。
代码1-1
public delegate void PassNotice(NoticeContext noticeContext);
public class Order
{
private NoticeContext _noticeContext;
public NoticeContext NoticeContext
{
get { return _noticeContext; }
set { _noticeContext = value; }
}
private PassNotice _befPassNotice;
public event PassNotice BefPassNotice
{
add
{
_befPassNotice += value;
}
remove
{
_befPassNotice -= value;
}
}
private PassNotice _latPassNotice;
public event PassNotice LatPassNotice
{
add
{
_latPassNotice += value;
}
remove
{
_latPassNotice -= value;
}
}
private void SendGoods()
{
Console.WriteLine("发货…… 请等待接收");
}
public void Start()
{
if (_befPassNotice != null)
{
_befPassNotice(NoticeContext);
}
if (NoticeContext.IsSend)
{
Console.WriteLine("服务端:客户端已确认可以发货");
SendGoods();
if (_latPassNotice != null)
{
_latPassNotice(NoticeContext);
}
if (NoticeContext.IsAccept)
{
Console.WriteLine("服务端:客户端已收货");
}
}
else
{
Console.WriteLine("服务端:等待客户端确认");
}
}
}
Order类代表着订单(这里这个比喻有点不恰当),里面有着两个PassNotice委托类型的事件BefPassNotice、LatPassNotice,分别表示订单发货前的验证和发货后的客户可针对的操作(对应着HttpApplication中的各种事件),再看一下客户类
代码1-2
public class NoticeContext
{
public bool IsSend { get; set; }
public bool IsAccept { get; set; }
}
public class Customer
{
private Order _Order;
public Customer(Order order)
{
_Order = order;
_Order.BefPassNotice += new PassNotice(_Order_BefPassNotice);
_Order.LatPassNotice += new PassNotice(_Order_LatPassNotice);
}
void _Order_LatPassNotice(NoticeContext noticeContext)
{
noticeContext.IsAccept = true;
Console.WriteLine("客户端:接收货物");
}
void _Order_BefPassNotice(NoticeContext noticeContext)
{
noticeContext.IsSend = true;
Console.WriteLine("客户端:可以发货");
}
}
View Code
这里Customer类有着对Order类的引用,并且订阅Order类的事件,从而可以处理到Order类中的NoticeContex类型值(类似于HttpModule)。
调用
代码1-3
Order order = new Order();
Customer customer = new Customer(order);
order.NoticeContext = new NoticeContext() { IsAccept = false, IsSend = false };
order.Start();
结果如图2所示
图2
示例中还有很多地方没有说明白,只演示了一个大概的模型,还有要说的就是Order类型对应着的处理是单一的(示例中欠妥),就好比HttpApplication只能对应着一个请求一样,当前的上下文信息中也只是存放着当前请求的信息。
在代码1-3中对Customer是直接的调用的,而在ASP.NET中不是这样的。
下一篇将会讲到MVC中的路由部分,对于这个学前篇系列慢慢来完善吧。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。