AspNetCore Custom/Explicit Swagger OperationId

AspNetCore Custom/Explicit Swagger OperationId

我正在使用 aspnet core 2.2 创建 restful API。我有一个标准设置,其中每个模型都有自己的控制器,带有 GETPOST 操作。我正在使用 Swashbuckle.AspNetCore NUGET 包并使用 Microsoft 文档中的 this 文章。

现在,当我查看生成的 swagger 文件时,它有多个 GET 和 POST operationIds。如何在不使用 Swashbuckle.AspNetCore.Annotations 的情况下配置自定义 operationIds?

这是我的 Action 方法的样子:

[HttpPost]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
    Response result = await _context.PostAsync(request);
    return Ok(result);
}

我有多个控制器,它们都遵循相同的模式。

我的创业公司 class 看起来像这样:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    ...
}

我已经看过 解决方案,但不想走那条路。

在花了几个小时寻找最佳解决方案后,我找到了 2 种方法:

选项 1:基于约定 - SwaggerGen 有一个选项可以设置 CustomOperationIds。所以你可以简单地设置它使用 ControllerName_HttpMethod 像这样:

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
    c.SwaggerDoc("v1", new Info { Title = "ID&V API", Version = "v1" });
});

这将按照 ControllerName_HttpMethod 惯例将 operationIds 添加到您的所有方法。

选项 2:基于 ActionFilter/Attribute - 您可以配置每个 Action 方法(就像您对 SwaggerOperation 操作过滤器所做的那样,只需添加一个 Name 属性 到您的 HTTP 动词操作过滤器,如下所示:

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

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

Swashbuckle.AspNetCore 可以找到文档 here