1. 程式人生 > >asp.net Mvc 動態創建Controller

asp.net Mvc 動態創建Controller

字段 control == return 註冊 gis nor factory request

有這麽個需求,Urls如下:

http://localhost:52804

http://localhost:52804/home/test

http://localhost:52804/test1

http://localhost:52804/test1/aaa

http://localhost:52804/test1/bbb

http://localhost:52804/test2/aaa

http://localhost:52804/test2/bbb

第1和2條url是代表真實存在Controller的,後面的都是需要動態生成Controller的,為了實現這樣的需求,通過查找資料,可以重寫DefaultControllerFactory實現。步驟和代碼如下:

1、新建FolderControllerFactory.cs繼承自DefaultControllerFactory

 public class FolderControllerFactory : DefaultControllerFactory
    {
        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            var controllerType = GetControllerType(requestContext, controllerName);
            
// 如果controller不存在,替換為FolderController if (controllerType == null) { // 用路由字段動態構建路由變量 var dynamicRoute = string.Join("/", requestContext.RouteData.Values.Values); controllerName = "Folder"; controllerType = GetControllerType(requestContext, controllerName); requestContext.RouteData.Values[
"Controller"] = controllerName; requestContext.RouteData.Values["action"] = "Index"; requestContext.RouteData.Values["dynamicRoute"] = dynamicRoute; } IController controller = GetControllerInstance(requestContext,controllerType); return controller; } }

2、新建FolderController

public class FolderController : Controller
    {
        // GET: Folder
        public ActionResult Index(string dynamicRoute)
        {            
            string viewFile = "/Views/" + dynamicRoute + ".cshtml";
            return View(viewFile);
        }
    }

3、修改路由規則

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapRoute(
                "CatchAll",
                "{*dynamicRoute}",
                new { controller = "Folder", action = "Index" }
            );
        }

4、在Global.asax註冊自定義的FolderControllerFactory

protected void Application_Start()
        {
            ControllerBuilder.Current.SetControllerFactory(new FolderControllerFactory());
            AreaRegistration.RegisterAllAreas();            
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

5、在Views下新建一些文件夾和View作為測試,如圖:

技術分享

測試結果如下:

技術分享

技術分享

這樣就簡單的實現了通過博主的需求。。

完整工程下載:

http://files.cnblogs.com/files/wxb8/DynamicController.zip

asp.net Mvc 動態創建Controller