开发者

MVC : Separate admin controllers

I was wandering if there is option to do the following

If I call "admin/Category" - to call "CategoryAdminController" If I call "Category" - to call "CategoryController"

It is very easy to do this via routing and custom controller factory. Here is the solution:

// 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() })
            });

Than create custom controller factory

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);
        }

 publi开发者_如何学JAVAc override IController CreateController(RequestContext requestContext, string controllerName)
        {
            _requestContext = requestContext;
            return base.CreateController(requestContext, controllerName);

}
}

I would like if anybody know some different/better solution.


You can do this quite simply with two route handlers:

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

and then:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜