llCorvinuSll llCorvinuSll - 3 months ago 28
C# Question

Attribute Routing for ApiControllers from external assembly

I have a large ASP.NET MVC 5 application, and now I want to implement Web API for it. But I want to put ApiControllers in a separate project.

I have problem with organizing routes for the Web API:

I want my main application Routes by

host/*


And the API maps on

host/api/*


And for the API, I want to use Attribute Routing, but can't setup WebApiConfig with proper way.

How to organize this, retaining the ability to use "Attribute Routing"?

Answer

I found the solution:

For ApiControllers it is not necessary to reimplement Factories.

In project Web (main), we need:

  1. Add dependency to project with ApiControllers

  2. Edit Global.asax this way

    replace:

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    

    to

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. in WebApiConfig.Register

    config.MapHttpAttributeRoutes();
    

    to enable Attribute Routing.

Now the Web API engine can find all ApiControllers in the Scope.