2009-11-18 91 views
1

我是遊蕩,如果有選擇做以下MVC:獨立管理控制器

如果我叫 「管理/類別」 - 叫「CategoryAdminController」 如果我叫 「類別」 - 叫「 CategoryController「

通過路由和自定義控制器工廠很容易做到這一點。這裏是解決方案:

// add route 
routes.Add(new Route("{culture}/admin/{controller}/{action}/{*id}", new MvcRouteHandler()) 
      { 
       Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "", culture = LocalizationManager.DefaultCulture.Name, controllerSufix = "Admin" }), 
       Constraints = new RouteValueDictionary(new { culture = new CultureRouteConstraint() }) 
      }); 

比創建自定義控制器工廠

public class CmsControllerFactory : DefaultControllerFactory 
    { 
     RequestContext _requestContext; 

     protected override Type GetControllerType(string controllerName) 
     { 
      if (_requestContext.RouteData.Values.ContainsKey("controllerSufix")) 
      { 
       string sufix = (string)_requestContext.RouteData.Values["controllerSufix"]; 
       Type type = base.GetControllerType(String.Concat(controllerName, sufix)); 
       if (type != null) 
        return type; 
      } 
      return base.GetControllerType(controllerName); 
     } 

public override IController CreateController(RequestContext requestContext, string controllerName) 
     { 
      _requestContext = requestContext; 
      return base.CreateController(requestContext, controllerName); 

} 
} 

如果有人知道一些不同/更好的解決辦法,我想。

+1

只注意到,即使我稱之爲類別「本地主機/分類」操作鏈接這種情況下, >索引視圖像<%= Html.ActionLink(「Something」,「I​​ndex」)%> 將在其中插入「admin」部分,所以我仍在尋找解決方案。 – 2009-11-18 09:35:53

回答

2

你可以做到這一點很簡單,有兩個途徑處理:

routes.MapRoute(
    "Admin",            
    "/admin/category/{id}",       
    new { controller = "CategoryAdminController", action = "Index", id = "" } 
); 

然後:

routes.MapRoute(
    "Standard",            
    "/category/{id}",       
    new { controller = "CategoryController", action = "Index", id = "" } 
); 
+0

是的,這也是一個解決方案,但我在談論約定,你可以調用「admin/category」來調用CategoryAdminController,或者只是「Category」來調用「CategoryController」,而不用爲每個案例添加新的路由到Route集合。 – 2009-11-18 12:09:14