关于控制器工厂的扩展,要么通过实现IControllerFactory接口,要么通过继承DefaultControllerFactory。本篇中,我想体验的是:
1、当请求经过路由,controller, action名称是以key/value键值对形式存放的,我们可以通过RequestContext.RouteData.Values["action"]和RequestContext.RouteData.Values["controller"]获取action或controller的名称。
2、通过实现IControllerFactory接口,根据请求中的controller名称,来返回不同类型的IController。
3、另外,当请求到了某个Controller, 通过实现IController接口,根据从路由中拿到的action名称,可以自定义响应。
□ HomeController:
public ActionResult Index()
{
return Content("我来自NewProduct/Index");
}
□ NewProductController:
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class NewProductController : Controller
{
public ActionResult Index()
{
return Content("我来自NewProduct/Index");
}
}
}
□ OldProductController:
通过实现IController接口,根据从路由中拿到的action名称,实现自定义响应。
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class OldProductController : IController
{
public void Execute(System.Web.Routing.RequestContext requestContext)
{
//action名称是以key/value保存的
string actionName = requestContext.RouteData.Values["action"].ToString().ToLower();
switch (actionName)
{
case "index":
requestContext.HttpContext.Response.Write("我来自OldProduct/Index");
break;
default:
requestContext.HttpContext.Response.Write("我来自OleProduct/" + actionName);
break;
}
}
}
}
□ MyControllerFactory
实现IControllerFactory接口,当controller名称是new的时候,返回NewProductController;当controller名称是old,返回OldProductController;默认情况下返回Home/Index。
using System;
using System.Web.Mvc;
using System.Web.SessionState;
using MvcApplication1.Controllers;
namespace MvcApplication1.Extension
{
public class MyControllerFactory : IControllerFactory
{
public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
Type controllerType = null;
switch (controllerName)
{
case "new":
controllerType = typeof (NewProductController);
break;
case "old":
controllerType = typeof (OldProductController);
break;
default:
controllerType = typeof (HomeController);
requestContext.RouteData.Values["controller"] = "Home";
requestContext.RouteData.Values["action"] = "index";
break;
}
return controllerType == null ? null : (IController) DependencyResolver.Current.GetService(controllerType);
}
public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
{
return SessionStateBehavior.Default;
}
public void ReleaseController(IController controller)
{
IDisposable disposable = controller as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
}
全局注册自定义控制器工厂。
protected void Application_Start()
{
......
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
}
参考资料:
Controller Factory and Action Invoker Part 1