Common ApiController Base Class with Swagger

2.3k Views Asked by At

So i implemented my first REST API application and everything is working fine, including Swagger (I used Swashbuckle and can test my APIs)

In the documentation I read, "...Controller must extend from ApiController...". I get that. However, how literally should I take that statement? What I wanted to do is avoid replication of code in each of my ApiController extensions. For instance I have two controllers - ProductController and DeviceController - both of which extend ApiController. I created class BaseController extending ApiController. Then I changed base class for both Product Controller and Device Controller to Base Controller

public class BaseController : ApiController
{
}

public class ProductController : BaseController // ApiController
{
}

public class DeviceController : BaseController // ApiController
{
}

1) Swagger application has error as soon as I hit the /swagger URL. 2) I really don't want my BaseController to even serve any requests. All I want is to have common helper methods I can use in all of my controllers such as ProductController and DeviceController.

Any advice appreciated.

2

There are 2 best solutions below

0
On

In my case [ApiExplorerSettings(IgnoreApi = true)] also removes all inhering controllers.

I had to mark the methods in the base controller with the [NonAction] filter as described here: https://stackoverflow.com/a/63845979/218408

Dotnet 5

4
On

Try using the @ApiIgnore annotation at the controller level.

   [ApiExplorerSettings(IgnoreApi = true)]
    public class BaseController : ApiController
    {
    }