将 Swagger 描述添加到最小的 .NET 6 API

Enr*_*ico 17 c# swagger swagger-ui .net-6.0 minimal-apis

我在 .NET 6 中有一个小项目,其中包含类似的最少 API

app.MapGet("/clients",
     async (IClientRepository repo) =>
     {
          var results = await repo.GetClientsAsync();
          return mapper.Map<IEnumerable<ClientModel>>(results);
     });
Run Code Online (Sandbox Code Playgroud)

SwaggerUI我可以使用这个 API,但我找不到向其添加描述的方法(尽管在项目设置中我检查了创建 API XML 文档)。

在此输入图像描述

如何添加 XML 注释?

Gur*_*ron 28

目前,对最小 API 的开放 API 文档的支持相当少,据我所知,不允许添加描述/摘要。.NET 7计划有一项功能来添加描述。也很快Swashbuckle应该考虑EndpointMetadata进行注释

还有相关问题

更新

通过Swashbucklenuget 包的最新更新,Swashbuckle.AspNetCore.Annotations您可以向端点添加描述:

builder.Services.AddSwaggerGen(opts => opts.EnableAnnotations());

app.MapGet("/weatherforecast", () =>
{
    // Implementation
})
.WithMetadata(new SwaggerOperationAttribute(summary: "Summary", description: "Descritption Test"));

// Or

app.MapGet("/weatherforecast1", [SwaggerOperation(summary: "Summary1", description: "Descritption Test1")] () =>
{
    // Implementation
});
Run Code Online (Sandbox Code Playgroud)

更新2

对于.NET 7和最新的Swashbuckle.AspNetCore封装WithDescription方法也可以使用:

builder.Services.AddSwaggerGen();
...

app.MapGet("/weatherforecast", () =>
{
    // implementation
})
.WithDescription("Some Method Description")
.WithOpenApi();
Run Code Online (Sandbox Code Playgroud)

或者与EndpointDescriptionAttribute

app.MapGet("/weatherforecast1", [EndpointDescription("Some Attribute description")] () =>
{
    // implementation
})
.WithOpenApi();
Run Code Online (Sandbox Code Playgroud)

  • 我想补充一点,您可以在 [Microsoft.AspNetCore.OpenApi](https://www.nuget.org/packages/Microsoft.AspNetCore.OpenApi/) NuGet 包中找到“WithOpenApi”方法。 (3认同)
  • `WithOpenApi` 扩展方法还支持通过传递委托来设置操作的描述,如 `operation =&gt; operation.Description = "foo"; 返回操作;`。它更加健壮一些,因为您可以修改整个操作。 (2认同)

dag*_*ett 14

包裹Swashbuckle.AspNetCore.Annotations 6.3

...
builder.Services.AddSwaggerGen(c => c.EnableAnnotations());

var app = builder.build();

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)

更多示例在这里 https://github.com/domaindrivendev/Swashbuckle.AspNetCore#enrich-operation-metadata


bug*_*ggy 14

1.安装包

dotnet add package Swashbuckle.AspNetCore.Annotations
Run Code Online (Sandbox Code Playgroud)

2. 编写代码

dotnet add package Swashbuckle.AspNetCore.Annotations
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述