简体   繁体   English

带有 Swagger 的通用 ApiController 基类

[英]Common ApiController Base Class with Swagger

So i implemented my first REST API application and everything is working fine, including Swagger (I used Swashbuckle and can test my APIs)所以我实现了我的第一个 REST API 应用程序并且一切正常,包括 Swagger(我使用了 Swashbuckle 并且可以测试我的 API)

In the documentation I read, "...Controller must extend from ApiController ...".在我阅读的文档中,“...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.我想要做的是避免在我的每个ApiController扩展中复制代码。 For instance I have two controllers - ProductController and DeviceController - both of which extend ApiController .例如,我有两个控制器 - ProductControllerDeviceController - 它们都扩展了ApiController I created class BaseController extending ApiController .我创建的类BaseController延伸ApiController Then I changed base class for both Product Controller and Device Controller to Base Controller然后我将 Product Controller 和 Device Controller 的基类更改为 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. 1) 一旦我点击 /swagger URL,Swagger 应用程序就会出错。 2) I really don't want my BaseController to even serve any requests. 2)我真的不希望我的BaseController甚至为任何请求提供服务。 All I want is to have common helper methods I can use in all of my controllers such as ProductController and DeviceController .我想要的只是拥有可以在我的所有控制器(例如ProductControllerDeviceController使用的通用辅助方法。

Any advice appreciated.任何建议表示赞赏。

Try using the @ApiIgnore annotation at the controller level.尝试在控制器级别使用 @ApiIgnore 注释。

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

In my case [ApiExplorerSettings(IgnoreApi = true)] also removes all inhering controllers.在我的例子中[ApiExplorerSettings(IgnoreApi = true)]也删除了所有继承的控制器。

I had to mark the methods in the base controller with the [NonAction] filter as described here: https://stackoverflow.com/a/63845979/218408我必须使用[NonAction]过滤器标记基本控制器中的方法,如下所述: https : [NonAction]

Dotnet 5网络5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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