【问题标题】:Does Swagger (Asp.Net Core) have a controller description?Swagger (Asp.Net Core) 有控制器描述吗?
【发布时间】:2016-11-01 22:58:26
【问题描述】:

我正在构建一个 REST 服务,它将托管多个控制器(微服务)。作为一个整体,我们将服务称为“Bob”。所以大摇大摆地显示“鲍勃”/“鲍勃微服务的集合”。然后列出控制器名称。现在,它只显示 XYZ、ABC 等。有没有办法可以大摇大摆地显示“XYZ - XYZ API 的集合”或类似的东西?

似乎 swagger 在方法上显示 ///Summary,但在控制器上却没有。

【问题讨论】:

  • 快速说明:多控制器肯定不是微服务
  • @KierenJohnstone -- 从这个意义上说,这就是他们想要的方式。显然不是纯 REST ......但我们将在控制器中使用路由指定多个 POST 方法。因此,您将能够发布到 /Bob/XYZ/method1、/Bob/XYZ/method2 等。这就是他们将其称为微服务的原因。
  • 这只是一个 Web API,可能不使用 REST。微服务是完全不同的东西:一组单独版本化、构建和(通常是自动)部署的服务,每个服务通常都有自己的数据存储和有界上下文。您只是在谈论“控制器”

标签: c# asp.net-core swagger swagger-ui


【解决方案1】:

如果您使用的是 Swashbuckle 4.0.x 和 ASP.NET Core 2.x,您可能会遇到类似的情况,通过包含 Swashbuckle.AspNetCore.Annotations 的 NuGet 包也可以工作。 p>

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
{
...
}

然后我在 ConfigureServices 方法中的 Startup.cs 招摇代码看起来像这样,(编辑以包括 Iain Carlin 的贡献以包括控制器标头 cmets):

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();
});

然后我的控制器将被装饰

【讨论】:

  • 请注意:需要添加nuget包Swashbuckle.AspNetCore.Annotations :) 谢谢你的帮助!
  • 确保将其添加到您的 .csproj 文件中。或者你会得到一个 .xml 文件不存在错误 true
【解决方案2】:

我一直在寻找类似的答案,并希望能够使用控制器类上的摘要 XML cmets 来提供控制器描述。事实证明,您可以通过在启动时的 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]

显示为:

【讨论】:

  • 好!但是这会将 cmets 添加到所有控制器,如果我只需要注释一些(比如“进行中”),然后使用 SwaggerTag
【解决方案3】:

有没有办法让大摇大摆地展示“XYZ - XYZ API 的集合”

是的。这是最简单的方法之一。 Swagger 的 ASP.NET Core 版本利用 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() 方法返回与每个动作的控制器关联的GroupName。然后我们可以将ApiExplorerSettings 属性放在每个控制器上,而不是放在每个动作上。

【讨论】:

  • 谢谢Shaun,看来我需要把它放在控制器中的每个方法上?我试着把它放在课堂上(因为属性说它是允许的),但 Swagger 没有选择它。
  • @SledgeHammer 是的。我们确实需要将该属性放在控制器中的每个方法上。如果时间允许,我将研究一种在控制器级别应用它的方法。
  • 这将在 .Net4.8 Web API 中工作还是仅在 .Core 中工作
【解决方案4】:

您也可以为此使用SwaggerOperationAttribute

public class MyController 
{
    [SwaggerOperation(Tags = new[] { "XYZ - A collection of XYZ APIs" })]
    public IActionResult MyAction() 
    {
    }
}

在 Swashbuckle.AspNetCore 版本 1.0.0-rc3 中,ApiExplorerSettingsAttribute 用于在特定 Swagger 文档中包含操作。

【讨论】:

    【解决方案5】:

    我知道这是旧的,但以防万一其他人登陆这里 - 寻找核心版本的答案 - 为了完整起见,我将留下另一个简单的选择。来自docs

    自定义操作标签(例如用于 UI 分组)

    Swagger 规范允许将一个或多个“标签”分配给操作。 Swagger 生成器会将控制器名称分配为默认标记。如果您使用 SwaggerUI 中间件,这将特别有趣,因为它使用此值对操作进行分组。

    您可以通过提供一个按约定应用标签的函数来覆盖默认标签。例如,以下配置将通过 HTTP 方法标记并因此在 UI 中对操作进行分组:

    services.AddSwaggerGen(c =>
    {
        ...
        c.TagActionsBy(api => api.HttpMethod);
    };
    

    使用这种方式,您可以使用最适合您需求的逻辑来标记您的端点。您将 lambda 传递给 TagActionsBy 方法并返回您想要的标签。

    对于您提供的示例,我们可以这样做:

    services.AddSwaggerGen(c =>
    {
        ...
        c.TagActionsBy(api => "XYZ - A collection of XYZ APIs");
    };
    

    希望这会有所帮助!

    【讨论】:

      【解决方案6】:

      有一个新属性,替换了 NSwag.Annotations 中旧的 [SwaggerTag(...)]:

      [OpenApiTag("This is name", Description = "This is description")]
      

      哪些结果:

      注意,必须指定第一个属性name,您可以保持名称不变或重命名控制器。

      不幸的是,似乎没有简单的解决方案可以将 ///summary cmets 添加到文档中。这种方法无需任何额外配置即可工作。

      【讨论】:

      • 我已经从 nuget 添加了 NSwag.Annotations 并在控制器上添加了 OpenApiTag,但它没有大张旗鼓地显示。还有其他配置需要说明吗?
      • @GobindGupta,抱歉,我不记得设置任何其他内容,但可能是该项目之前已经设置好了。
      【解决方案7】:

      将 NSwag 用于 .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";
                  };
              });
      

      方法:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 添加这个:

              //CONFIG: Configure NSwag
              app.UseOpenApi();
              app.UseSwaggerUi3();
      

      然后,在控制器类和方法的顶部,只需添加一个摘要,例如:

      /// <summary>
      /// your description
      /// </summary>
      [ApiController]
      [Route(your route)]
      public class NameController : ControllerBase
      

      它会像现场演示一样干净整洁:https://swagger.io/tools/swagger-ui/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-06
        • 2018-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多