有没有什么方法可以配置 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/