Swagger 响应描述未显示

The*_*yer 13 c# swagger swagger-ui .net-core

我目前正在尝试在 Swagger UI 中显示特定响应的描述,但似乎没有一个文档真正涵盖了该响应的所有方面,以及我在Swashbuckle 和 ASP 入门中尝试过的所有示例。 NET Core不适用于 .NET Core 3.1...

        /// <summary>
        /// Test route...
        /// </summary>
        /// <returns></returns>
        /// <response code="200">This is a test</response>
        [HttpGet]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public IActionResult Get()
        {
            return Ok("Hello World");
        }
Run Code Online (Sandbox Code Playgroud)

我的 .csproj 还包含以下内容:

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

Swagger UI 最终看起来像这样(正如您所看到的,“Descriptipn”列不包含“这是一个测试”文本,因为它可能应该包含在内)。我错过了什么吗?

图片预览

我也添加了[SwaggerResponse(StatusCodes.Status200OK, ...)]它,但没有任何改变。

The*_*yer 21

事实证明,[SwaggerResponse]工作正常,但在此之前,我需要在我的启动中“启用注释”......

    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "Some API",
            Version = "v1"
        });

        config.EnableAnnotations();
    });
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您需要安装 [Swashbuckle.AspNetCore.Annotations](https://github.com/domaindrivendev/Swashbuckle.AspNetCore#swashbuckleaspnetcoreannotations) NuGet 包。 (3认同)

Ale*_*aus 9

从 .NET v6 开始,有两种管理 API 的方法:经典 API 控制器最小 API。它们有很大不同,所以我在下面提供两个答案。

对于经典/传统 API 控制器

根据官方文档,它是通过 XML 注释与属性组合完成的ProducesResponseType

<response code="201">This is a test</response>
[ProducesResponseType(StatusCodes.Status201Created)]
Run Code Online (Sandbox Code Playgroud)

评论需要链接到Swagger

builder.Services.AddSwaggerGen(options =>
{
    // using System.Reflection;
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
Run Code Online (Sandbox Code Playgroud)

对于最小的 API

在 .NET 6 中,最小的 API 相当原始,NSwag 和 Swashbuckle 的支持都不完整。它只支持老式属性(根据SO 上的这篇文章):

app.MapGet("/clients",
    [SwaggerOperation(
        Summary = "returns clients",
        Description = "more description on get `clients`")]
    [SwaggerResponse(200, "success")]
    [SwaggerResponse(500, "some failure")]
    async (IClientRepository repo) =>
    {
        var results = await repo.GetClientsAsync();
        return mapper.Map<IEnumerable<ClientModel>>(results);
    }).WithTags("Clients");
Run Code Online (Sandbox Code Playgroud)

.NET 7 添加了几个有用的扩展方法。其中之一是Produces,它提供类型和 HTTP 代码,但缺少方便的消息:

app.MapGet("/clients",
    async (IClientRepository repo) =>
    {
        var results = await repo.GetClientsAsync();
        return mapper.Map<IEnumerable<ClientModel>>(results);
    }).Produces<IEnumerable<ClientModel>>(StatusCodes.Status200OK)
      .WithTags("Clients")
      .WithSummary("returns clients")
      .WithDescription("more description on get `clients`");
Run Code Online (Sandbox Code Playgroud)

使用这些扩展方法的优点是您可以批量应用它们,例如:

var routes = new[] { 
    app.MapGet("/clients", (IClientRepository repo) => repo.GetClients()),
    app.MapGet("/users", (IUserRepository repo) => repo.GetUsers()),
};
foreach (var route in routes)                               
    route.WithTags("Lists");    
Run Code Online (Sandbox Code Playgroud)