Swagger(Asp.Net 核心)是否有控制器描述?
Does Swagger (Asp.Net Core) have a controller description?
我正在构建一个将托管多个控制器(微服务)的 REST 服务。作为一个整体,让我们调用服务 "Bob"。所以 swagger 显示 "Bob" / "A collection of Bob Microservices"。然后列出控制器名称。现在,它只显示 XYZ、ABC 等。有没有办法让 swagger show "XYZ - A collection of XYZ APIs" 或类似的东西?
似乎 swagger 在方法上显示了 ///Summary,但在控制器上没有显示。
Is there a way to maybe have swagger show "XYZ - A collection of XYZ APIs"
是的。这是最简单的方法之一。 ASP.NET 核心版本的 Swagger 利用了 ApiExplorerSettings
属性。你可以设置GroupName
。
public class BobController
{
[ApiExplorerSettings(GroupName="XYZ - A collection of XYZ APIs")]
public IActionResult MyAction()
{
...
}
}
组名称出现在 Swagger UI 中,组的操作列为下面的操作。
编辑: 这是一个基于 SledgeHammer 评论的想法。
Swagger ASP.NET Core 使用 IApiDescriptionGroupCollectionProvider
来构建其描述组。我们可以实现我们自己的,使用默认的 ApiDescriptionGroupCollectionProvider
作为灵感,并在 Startup.ConfigureServices
期间注册我们的提供者。我们的实现将使 ApiDescriptionGroups()
方法 return 与每个动作的控制器关联的 GroupName
。然后我们可以将 ApiExplorerSettings
属性放在每个控制器上,而不是放在每个操作上。
您也可以使用 SwaggerOperationAttribute:
public class MyController
{
[SwaggerOperation(Tags = new[] { "XYZ - A collection of XYZ APIs" })]
public IActionResult MyAction()
{
}
}
在 Swashbuckle.AspNetCore 版本 1.0.0-rc3 中,ApiExplorerSettingsAttribute 用于在特定的 Swagger 文档中包含一个动作。
我知道这是旧的,但以防万一有人来到这里 - 寻找核心版本的答案 - 为了完整起见,我将留下另一个简单的选择。来自 docs:
自定义操作标签(例如 UI 分组)
Swagger 规范允许为一项操作分配一个或多个“标签”。 Swagger 生成器会将控制器名称分配为默认标记。如果您使用 SwaggerUI 中间件,这将特别有趣,因为它使用此值对操作进行分组。
您可以通过提供按约定应用标签的函数来覆盖默认标签。例如,以下配置将通过 HTTP 方法标记,并因此在 UI 中对操作进行分组:
services.AddSwaggerGen(c =>
{
...
c.TagActionsBy(api => api.HttpMethod);
};
通过这种方式,您可以使用最适合您需求的逻辑来标记您的端点。您将 lambda 传递给 TagActionsBy
方法和 return 您想要的标签。
对于您提供的示例,我们可以做:
services.AddSwaggerGen(c =>
{
...
c.TagActionsBy(api => "XYZ - A collection of XYZ APIs");
};
希望对您有所帮助!
如果您使用的是 Swashbuckle 4.0.x 和 ASP.NET Core 2.x,您可能拥有类似这样的东西,它也可以通过包含 的 NuGet 包来工作Swashbuckle.AspNetCore.Annotations.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;
namespace MyExample.Controllers
{
/// <summary>
/// Example of a .NET Core controller based on the controller name
/// api/[controller] on ValuesController becomes api/values
/// endpoint: "/Values" from [controller] and name of controller , which is "ValuesController"
/// </summary>
[Route("[controller]")]
[ApiController]
[SwaggerTag("This is an example controller generated by ASP.NET Core 2.x")]
public class ValuesController : ControllerBase
{
...
}
然后我的 Startup.cs ConfigureServices 方法中的 swagger 代码如下所示(经过编辑以包括 Iain Carlin 的贡献以包含控制器 header 评论):
services.AddSwaggerGen(c =>
{
// Set Title and version
c.SwaggerDoc("v1", new Info { Title = "My Example API", Version = "v1", Description = "The API for my application" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// pick comments from classes, including controller summary comments
c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
// _OR_ enable the annotations on Controller classes [SwaggerTag], if no class comments present
c.EnableAnnotations();
});
然后我的 Controller 会得到装饰
我一直在寻找类似的答案,希望能够使用控制器 class 上的摘要 XML 评论来提供控制器描述。事实证明,您可以通过在启动时的 Swagger 配置中添加 includeControllerXmlComments: true 来做到这一点:
services.AddSwaggerGen(c =>
{
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
});
那么:
/// <summary>
/// My controller description
/// </summary>
[Route("api/[controller]")]
[ApiController]
显示为:
有一个新属性,替换了 NSwag.Annotations 中的旧 [SwaggerTag(...)]:
[OpenApiTag("This is name", Description = "This is description")]
结果为:
注意,必须指定第一个属性名称,您可以保持名称不变或重命名控制器。
不幸的是,似乎没有简单的解决方案可以将 /// 摘要注释添加到文档中。这种方法无需任何额外配置即可工作。
使用 NSwag for .NET Core 3.1 的简单方法。只需添加下面的代码,您就可以很好地了解控制器和 API。在 swagger 页面的顶部加上一些描述。
Startup.cs - 方法:public void ConfigureServices(IServiceCollection services)
services.AddSwaggerDocument(config =>
{
config.OperationProcessors.Add(
new AspNetCoreOperationSecurityScopeProcessor("JWT"));
// Add summary to the controller
config.UseControllerSummaryAsTagDescription = true;
// Add JWT authorization option at the top
config.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Type into the textbox: Bearer {your JWT Token}"
});
config.PostProcess = document =>
{
document.Info.Version = "1";
document.Info.Title = "title";
document.Info.Description = "description";
};
});
方法:publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env)
添加:
//CONFIG: Configure NSwag
app.UseOpenApi();
app.UseSwaggerUi3();
然后,在controller class 和methods 的顶部,添加一个摘要,例如:
/// <summary>
/// your description
/// </summary>
[ApiController]
[Route(your route)]
public class NameController : ControllerBase
它会像这里的现场演示一样干净整洁:https://swagger.io/tools/swagger-ui/
我正在构建一个将托管多个控制器(微服务)的 REST 服务。作为一个整体,让我们调用服务 "Bob"。所以 swagger 显示 "Bob" / "A collection of Bob Microservices"。然后列出控制器名称。现在,它只显示 XYZ、ABC 等。有没有办法让 swagger show "XYZ - A collection of XYZ APIs" 或类似的东西?
似乎 swagger 在方法上显示了 ///Summary,但在控制器上没有显示。
Is there a way to maybe have swagger show "XYZ - A collection of XYZ APIs"
是的。这是最简单的方法之一。 ASP.NET 核心版本的 Swagger 利用了 ApiExplorerSettings
属性。你可以设置GroupName
。
public class BobController
{
[ApiExplorerSettings(GroupName="XYZ - A collection of XYZ APIs")]
public IActionResult MyAction()
{
...
}
}
组名称出现在 Swagger UI 中,组的操作列为下面的操作。
编辑: 这是一个基于 SledgeHammer 评论的想法。
Swagger ASP.NET Core 使用 IApiDescriptionGroupCollectionProvider
来构建其描述组。我们可以实现我们自己的,使用默认的 ApiDescriptionGroupCollectionProvider
作为灵感,并在 Startup.ConfigureServices
期间注册我们的提供者。我们的实现将使 ApiDescriptionGroups()
方法 return 与每个动作的控制器关联的 GroupName
。然后我们可以将 ApiExplorerSettings
属性放在每个控制器上,而不是放在每个操作上。
您也可以使用 SwaggerOperationAttribute:
public class MyController
{
[SwaggerOperation(Tags = new[] { "XYZ - A collection of XYZ APIs" })]
public IActionResult MyAction()
{
}
}
在 Swashbuckle.AspNetCore 版本 1.0.0-rc3 中,ApiExplorerSettingsAttribute 用于在特定的 Swagger 文档中包含一个动作。
我知道这是旧的,但以防万一有人来到这里 - 寻找核心版本的答案 - 为了完整起见,我将留下另一个简单的选择。来自 docs:
自定义操作标签(例如 UI 分组)
Swagger 规范允许为一项操作分配一个或多个“标签”。 Swagger 生成器会将控制器名称分配为默认标记。如果您使用 SwaggerUI 中间件,这将特别有趣,因为它使用此值对操作进行分组。
您可以通过提供按约定应用标签的函数来覆盖默认标签。例如,以下配置将通过 HTTP 方法标记,并因此在 UI 中对操作进行分组:
services.AddSwaggerGen(c =>
{
...
c.TagActionsBy(api => api.HttpMethod);
};
通过这种方式,您可以使用最适合您需求的逻辑来标记您的端点。您将 lambda 传递给 TagActionsBy
方法和 return 您想要的标签。
对于您提供的示例,我们可以做:
services.AddSwaggerGen(c =>
{
...
c.TagActionsBy(api => "XYZ - A collection of XYZ APIs");
};
希望对您有所帮助!
如果您使用的是 Swashbuckle 4.0.x 和 ASP.NET Core 2.x,您可能拥有类似这样的东西,它也可以通过包含 的 NuGet 包来工作Swashbuckle.AspNetCore.Annotations.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;
namespace MyExample.Controllers
{
/// <summary>
/// Example of a .NET Core controller based on the controller name
/// api/[controller] on ValuesController becomes api/values
/// endpoint: "/Values" from [controller] and name of controller , which is "ValuesController"
/// </summary>
[Route("[controller]")]
[ApiController]
[SwaggerTag("This is an example controller generated by ASP.NET Core 2.x")]
public class ValuesController : ControllerBase
{
...
}
然后我的 Startup.cs ConfigureServices 方法中的 swagger 代码如下所示(经过编辑以包括 Iain Carlin 的贡献以包含控制器 header 评论):
services.AddSwaggerGen(c =>
{
// Set Title and version
c.SwaggerDoc("v1", new Info { Title = "My Example API", Version = "v1", Description = "The API for my application" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// pick comments from classes, including controller summary comments
c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
// _OR_ enable the annotations on Controller classes [SwaggerTag], if no class comments present
c.EnableAnnotations();
});
然后我的 Controller 会得到装饰
我一直在寻找类似的答案,希望能够使用控制器 class 上的摘要 XML 评论来提供控制器描述。事实证明,您可以通过在启动时的 Swagger 配置中添加 includeControllerXmlComments: true 来做到这一点:
services.AddSwaggerGen(c =>
{
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
});
那么:
/// <summary>
/// My controller description
/// </summary>
[Route("api/[controller]")]
[ApiController]
显示为:
有一个新属性,替换了 NSwag.Annotations 中的旧 [SwaggerTag(...)]:
[OpenApiTag("This is name", Description = "This is description")]
结果为:
注意,必须指定第一个属性名称,您可以保持名称不变或重命名控制器。
不幸的是,似乎没有简单的解决方案可以将 /// 摘要注释添加到文档中。这种方法无需任何额外配置即可工作。
使用 NSwag for .NET Core 3.1 的简单方法。只需添加下面的代码,您就可以很好地了解控制器和 API。在 swagger 页面的顶部加上一些描述。
Startup.cs - 方法:public void ConfigureServices(IServiceCollection services)
services.AddSwaggerDocument(config =>
{
config.OperationProcessors.Add(
new AspNetCoreOperationSecurityScopeProcessor("JWT"));
// Add summary to the controller
config.UseControllerSummaryAsTagDescription = true;
// Add JWT authorization option at the top
config.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Type into the textbox: Bearer {your JWT Token}"
});
config.PostProcess = document =>
{
document.Info.Version = "1";
document.Info.Title = "title";
document.Info.Description = "description";
};
});
方法:publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env) 添加:
//CONFIG: Configure NSwag
app.UseOpenApi();
app.UseSwaggerUi3();
然后,在controller class 和methods 的顶部,添加一个摘要,例如:
/// <summary>
/// your description
/// </summary>
[ApiController]
[Route(your route)]
public class NameController : ControllerBase
它会像这里的现场演示一样干净整洁:https://swagger.io/tools/swagger-ui/