Asp.net Mvc dynamically creates Controller and mvccontroller
Urls has the following requirements:
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
The 1st and 2 URLs represent the real existence of the Controller, and the latter all need to dynamically generate the Controller. To achieve this requirement, you can rewrite the defacontrocontrollerfactory implementation by searching for information. The steps and Code are as follows:
1. New FolderControllerFactory. cs inherits from DefaultControllerFactory
Public class FolderControllerFactory: DefaultControllerFactory {public override IController CreateController (RequestContext requestContext, string controllerName) {var controllerType = GetControllerType (requestContext, controllerName); // if the controller does not exist, replace with FolderController if (controllerType = null) {// use the routing field to dynamically build the routing variable 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. Create a FolderController
public class FolderController : Controller { // GET: Folder public ActionResult Index(string dynamicRoute) { string viewFile = "/Views/" + dynamicRoute + ".cshtml"; return View(viewFile); } }
3. Modify routing rules
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. register the custom FolderControllerFactory at Global. asax.
protected void Application_Start() { ControllerBuilder.Current.SetControllerFactory(new FolderControllerFactory()); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); }
5. Create some folders and Views under Views for testing,
The test results are as follows:
In this way, the needs of bloggers are simply realized ..
Download the complete project:
Http://files.cnblogs.com/files/wxb8/DynamicController.zip