0

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.

griftopia
  • 135
  • 1
  • 3
  • 10
  • 1
    Should just work. If you want help with the Swagger error, [edit] your question to include the Swagger error as well as your research. – CodeCaster Oct 03 '18 at 09:57
  • Inheritance isn't the best way to reuse code. ASP.NET Core, MVC, Web API, all provide ways to add reusable functionality through filters. – Panagiotis Kanavos Oct 03 '18 at 09:58
  • Creating your own base class should work anyway. You should declare it `abstract` if you don't want it to be instantiated. Perhaps a better way though would be to create C# extension methods that can be called by any controller? Or put those common methods in "helper" or "utility" classes that can be used when needed? – Panagiotis Kanavos Oct 03 '18 at 10:00
  • okay I made my BaseController abstract and that did the trick. Thank you! – griftopia Oct 03 '18 at 21:23

2 Answers2

1

Try using the @ApiIgnore annotation at the controller level.

   [ApiExplorerSettings(IgnoreApi = true)]
    public class BaseController : ApiController
    {
    }
go..
  • 958
  • 7
  • 15
1

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

Rahatur
  • 3,147
  • 3
  • 33
  • 49