Bern
Bern

Reputation: 7951

Multiple API controllers in different MVC Areas share the same namespace

I have 2 areas with 2 API controllers that have the same AI controller name, but different namespaces and which are configured via 2 different MapHttpRoute() calls with their unique names and routes. They also compile successfully without an issue. However, there are matching action methods in both and when I make a call to one I get back the exception below.

It's clear from the exception message that it's not supported but is there an elegant resolution so I don't have to name my API controllers uniquely despite being in separate namespaces?

Exception:

Multiple types were found that match the controller named 'SomethingApi'. This can happen if the route that services this request ('route-one/api/something/{action}') found multiple controllers defined with the same name but differing namespaces, which is not supported.

Route example:

public static void RegisterApiRoutes(HttpConfiguration config)
{
    // URL: /route-one/api/something/

    config.Routes.MapHttpRoute(
        "RoutOne.Api.Something",
        "route-one/api/something/{action}",
        new { controller = "SomethingApi" }
    );
}

Routes in both namespaces are called from the project's WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        RouteOneAreaRegistration.RegisterApiRoutes(config);
        RouteTwoAreaRegistration.RegisterApiRoutes(config);
    }
}

Upvotes: 0

Views: 1222

Answers (1)

danludwig
danludwig

Reputation: 47375

It seems to me like the elegant solution here is to name your ApiControllers differently. If they do not do the same thing, reflect that in the controller name. If they do the same thing, then you don't need separate controllers.

Another solution could be to have one controller with both of your different actions, named differently.

It's difficult to gauge why this is not an elegant way to resolve the problem given the abstract nature of your question. Perhaps if you told us what the controllers are named, how they differ, and why they are in separate areas, someone could provide a more appropriate answer for you.

Upvotes: 1

Related Questions