Route with namespace and area still complaining about multiple controller names

1.2k views Asked by At

I have a folder structure for my Sitecore MVC project as such:

Areas
-- Common
   -- Controllers
      -- HeaderController
   -- Models
   -- Views
-- Legal
   -- Controllers
      -- HeaderController
   -- Models
   -- Views

I am trying to invoke a controller from code, and I am passing the PageContent.Current.RequestContext, and filling it with the appropriate namespaces and area.

if (!String.IsNullOrWhiteSpace(Area))
            {
                PageContext.Current.RequestContext.RouteData.DataTokens["area"] = this.Area;
            }

            if (!String.IsNullOrWhiteSpace(AreaNameSpace))
            {
                PageContext.Current.RequestContext.RouteData.DataTokens["Namespaces"] = this.AreaNameSpace;
            }
            return ControllerBuilder.Current.GetControllerFactory().CreateController(PageContext.Current.RequestContext, this.ControllerName);
        }

But it still complains of the usual error:

Multiple types were found that match the controller named 'Header'.

I have the routes setup for each area, and the areas are all getting registered in the app_start in routeconfig.cs.

What could be the issue? Is this even possible?

2

There are 2 answers

2
Anupam Singh On

You have to configure your default route as :

routes.MapRoute(
    "Default",                                              
    "{controller}/{action}/{id}",                           
    new { controller = "Home", action = "Index", id = "" }, 
    new[]{"<namespace of you main controller (HeaderContriller)>"}                       
  );

You can refer my article here : http://www.c-sharpcorner.com/UploadFile/56fb14/working-with-routes-in-mvc-framework/

0
Renato Lemos On

For my case, the solution is that in MVC 5 instead of use

PageContext.Current.RequestContext.RouteData.DataTokens["Namespaces"] = this.AreaNameSpace;

you must define namespace as IEnumerable<string>

PageContext.Current.RequestContext.RouteData.DataTokens["Namespaces"] = new string[] { this.AreaNameSpace };

See Peter's commentary in asp.net mvc Find Controller By Name With Area.