软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > ASP.NET MVC 1.0 流程分析(MvcHandler & Controller)

ASP.NET MVC 1.0 流程分析(MvcHandler & Controller)

当 MVC 的脚步走到 System.Web.Mvc.MvcHandler,我们的分析工作就变得简单多了,因为可以直接在源代码中进行动态跟踪。

public class MvcHandler : IHttpHandler, IRequiresSessionState
{
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
AddVersionHeader(httpContext);

// Get the controller type
string controllerName = RequestContext.RouteData.GetRequiredString("controller");

// Instantiate the controller and call Execute
IControllerFactory factory = ControllerBuilder.GetControllerFactory();
IController controller = factory.CreateController(RequestContext, controllerName);

...

try
{
controller.Execute(RequestContext);
}
finally
{
factory.ReleaseController(controller);
}
}
}

AddVersionHeader 的作用是在添加一个 Http Header。

HTTP/1.1 200 OK
...
X-AspNetMvc-Version: 1.0
...

从 RequestContext.RouteData 中提取请求的 ControllerName,然后用 ControllerFactory 来生成 Controller 对象实例。

public class ControllerBuilder
{
public ControllerBuilder()
{
SetControllerFactory(new DefaultControllerFactory()
{
ControllerBuilder = this
});
}

public void SetControllerFactory(IControllerFactory controllerFactory)
{
_factoryThunk = () => controllerFactory;
}

public IControllerFactory GetControllerFactory()
{
IControllerFactory controllerFactoryInstance = _factoryThunk();
return controllerFactoryInstance;
}
}

ControllerBuilder.GetControllerFactory() 实际返回的是一个 DefaultControllerFactory 实例。

public class DefaultControllerFactory : IControllerFactory
{
public virtual IController CreateController(RequestContext requestContext, string controllerName)
{
...

RequestContext = requestContext;
Type controllerType = GetControllerType(controllerName);
IController controller = GetControllerInstance(controllerType);
return controller;
}

protected internal virtual IController GetControllerInstance(Type controllerType)
{
...

return (IController)Activator.CreateInstance(controllerType);

...
}
}

DefaultControllerFactory 内部做了些缓存(ControllerTypeCache)处理来加快后续访问速度。但核心代码很简单,通过 ControllerName 获取 ControllerType,然后反射创建 Controller 对象实例。有了这个对象实例,接下来的工作正式由 Controller.Execute() 接手。

public class MvcHandler : IHttpHandler, IRequiresSessionState
{
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
...

IControllerFactory factory = ControllerBuilder.GetControllerFactory();
IController controller = factory.CreateController(RequestContext, controllerName);

...

try
{
controller.Execute(RequestContext);
}
finally
{
factory.ReleaseController(controller);
}
}
}

相关阅读
网友评论
栏目导航
推荐软件