在创建Route时,除了传递url模式外,还默认帮我们传递了一个MvcRouteHandler,它实现了IRouteHandler接口。
步骤三、获取IHttpHandler接口对象
有了MvcRouteHandler,就可以调用它的GetHttpHandler方法获取IHttpHandler了,该方法实现如下:
protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//设置session状态
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext));
//返回一个实现了IHttpHandler的MvcHandler
return new MvcHandler(requestContext);
}
可以看到,它返回了一个MvcHandler,MvcHandler就实现了IHttpHandler接口。所以开头说的,请求本质都是交给HttpHandler的,其实MVC也是这样的,请求交给了MvcHandler处理。我们可以看MvcHandler定义和主要方法:
public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState
{
protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
{
IController controller;
IControllerFactory factory;
//这个方法里会激活Controller对象
ProcessRequestInit(httpContext, out controller, out factory);
IAsyncController asyncController = controller as IAsyncController;
if (asyncController != null)
{
// asynchronous controller
BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
{
try
{
//调用Controller的BeginExecute方法
return asyncController.BeginExecute(RequestContext, asyncCallback, asyncState);
}
catch
{
factory.ReleaseController(asyncController);
throw;
}
};
EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult)
{
try
{
asyncController.EndExecute(asyncResult);
}
finally
{
factory.ReleaseController(asyncController);
}
};
SynchronizationContext syncContext = SynchronizationContextUtil.GetSynchronizationContext();
AsyncCallback newCallback = AsyncUtil.WrapCallbackForSynchronizedExecution(callback, syncContext);
return AsyncResultWrapper.Begin(newCallback, state, beginDelegate, endDelegate, _processRequestTag);
}
else
{
// synchronous controller
Action action = delegate
{
try
{
controller.Execute(RequestContext);
}
finally
{
factory.ReleaseController(controller);
}
};
return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);
}
}
}
可以看到,MvcHandler的任务就是激活Controller,并执行它的Execute方法。这个过程和Webform里的页面处理是很相似的,.aspx请求到来,会根据虚拟路径找到实现IHttpHandler的Page(类似于路由机制根据url模式找到MvcHandler),然后进入Page的页面周期(类似于Mvc的激活Controller,然后执行Action过程)。








