C# .NET 仅为特定的 api Controller 或模块(项目)中的 api Controller 启用 Swagger UI

标签 c# .net asp.net-web-api2 swagger-ui

有没有什么方法可以配置 Swagger,使其只为解决方案中的某个 API Controller 或属于特定模块(带有解决方案的项目)的一组 API Controller 生成 UI 和文档?

我的解决方案由 50 多个项目组成,其中几个项目包含许多 API Controller ,但我只需要为其中一个位于特定项目中的项目启用 Swagger。

我知道 [ApiExplorerSettings(IgnoreApi = true)] 属性,但是这样我就需要将这个属性设置为我不需要的所有 API Controller ,我只想标记我想在其上使用 swagger 的特定 API Controller 。

有什么办法吗?

最佳答案

您可以在注册 Controller 时使用约定。

如果你创建一个新的 IActionModelConvention,像这样:

public class WhitelistControllersConvention : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        if (action.Controller.ControllerName == "Item")
        {
            action.ApiExplorer.IsVisible = true;
        }
        else
        {
            action.ApiExplorer.IsVisible = false;
        }
    }
}

然后在Startup中配置swagger时使用:

services.AddControllers(c =>
{
    c.Conventions.Add(new WhitelistControllersConvention());
});

然后您可以控制包含哪些 Controller 。在我的示例中,我只是根据名称(仅包括 ItemController)进行操作,但您可以更改它以标识您想要的 Controller ,但是您想要这样做。

关于C# .NET 仅为特定的 api Controller 或模块(项目)中的 api Controller 启用 Swagger UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63012460/

相关文章:

c# - 使用 C# 使用 Assembly GetManifestResourceStream 方法读取资源文件

c# - 如何在 WebBrowser 中以编程方式提交没有提交按钮的表单

c# - 使用 distance() 方法进行空间 Linq 查询

c# - 在 Web API 中创建属性模型绑定(bind)器

c# - Application.Run() 和按键事件

.net - 在 System.Reflection 中使用 Moles

.net - 无法设置 x :Name ="Root" on UserControl

.net - javascript表单发布提交在 IE 中工作,但在 Chrome 中不起作用

asp.net-web-api2 - Swashbuckle 5 和 multipart/form-data HelpPages

c# - 使用 NHibernate Queryover 内部连接 ​​3 个表