views:

76

answers:

1

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

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

}
}

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

+1  A: 

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 = "" }
 );
Jamie Dixon
Yes, that's also a solution, but I was talking about conventions where you can just call "admin/category" to call CategoryAdminController or just "Category" to call "CategoryController" without adding new routes into Route collections for each case.
Andrej Kaurin