Asp.Net核心Swashbuckle设置operationId

Але*_*оев 1 swagger swashbuckle asp.net-core

如何operationId在Asp.Net Core 2.1项目中设置swagger 属性?根据这篇文章,我应该使用,SwaggerOperationAttribute但在Swashbuckle.AspNetCore库中找不到它。也有一个IOperationFilter

  public interface IOperationFilter
  {
    void Apply(Operation operation, OperationFilterContext context);
  }
Run Code Online (Sandbox Code Playgroud)

而且我找不到为实现摇摇欲坠目的的任何实现。

Ian*_*cer 9

在最新版本中,Name[HttpGet]/添加参数会失败并出现异常,但在属性上添加参数似乎可行:[HttpPost]NameRoute

/// <summary>
/// Get all devices
/// </summary>
[Route("devices", Name = "GetAllDevices")]
[Authorize]
[HttpGet]
[Produces(typeof(Device[]))]
public async Task<IActionResult> GetAllDevices() { ...}
Run Code Online (Sandbox Code Playgroud)


CoO*_*oOl 8

还有2个其他选项,而无需编写任何额外的代码或添加额外的依赖项,例如 Swashbuckle.AspNetCore.Annotations

选项1:基于约定- SwaggerGen有设置选项CustomOperationIds。因此,您可以将其设置为ControllerName_HttpMethod如下所示:

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
    c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
});
Run Code Online (Sandbox Code Playgroud)

遵循ControllerName_HttpMethod约定,这会将operationIds添加到您的所有方法中。

选项2:基于ActionFilter / Attribute的-您可以配置每个Action方法(就像您SwaggerOperation通过简单地向NameHTTP谓词操作过滤器添加属性一样使用操作过滤器一样:

[HttpPost(Name="Post_Person")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
    Response result = await _context.PostAsync(request);
    return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)

这完全一样,[SwaggerOperation(OperationId = "Post_Person")]但不需要EnableAnnotations

  • @phoenix 一个迟来的答案。只需更改为 `ActionDescriptor.RouteValues["action"]` 即可。我也在下面添加了另一个答案。 (3认同)

Bow*_*wen 7

您还可以根据操作名称(即方法名称)生成操作 id,我发现这在生成 API 客户端时很方便。

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}");
    c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
});
Run Code Online (Sandbox Code Playgroud)