activebiz
activebiz

Reputation: 6220

WebAPI MVC Areas with same controller name

The structure of webapi is as follows:

App
   -Area
       -MyArea1
         - ControllerA (Route('api/myarea1/controllera'))
       -MyArea2
         - ControllerA  (Route('api/myarea2/controllera')) 

Problem is that the route api/myarea1/controllera and api/myarea2/controllera are not being resolved. It comes are 404.

I read somewhere we need to implement IHttpControllerSelector but not sure what is the simplest way to implement this. If there is any other way it can be done?

Any idea.

Edit: RouteConfig.cs

public class RouteConfig
{
    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 }
        );
    }
}

WebApiConfig.cs

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Edit 2:

   public override void RegisterArea(AreaRegistrationContext context) 
   {
        context.MapHttpRoute(
            name : "MyArea1_default",
            routeTemplate : "MyArea1{controller}/{action}/{id}",
            defaults : new { action = "Index", id = UrlParameter.Optional }
        );
    }

Upvotes: 1

Views: 1033

Answers (1)

timothyclifford
timothyclifford

Reputation: 6959

If you want to use controllers with the same name, you need to specify the namespace for each route configuration.

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapHttpRoute(
        name : "MyArea1_default",
        routeTemplate : "MyArea1{controller}/{action}/{id}",
        defaults : new { action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "Your.Controller.Namespace.Here" }  
    );
}

For your reference: http://haacked.com/archive/2010/01/12/ambiguous-controller-names.aspx/

Upvotes: 1

Related Questions