简体   繁体   中英

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM