【问题标题】:AspNetCore Custom/Explicit Swagger OperationIdAspNetCore 自定义/显式 Swagger OperationId
【发布时间】:2019-06-15 01:03:56
【问题描述】:

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

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

这是我的 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);
}

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

我的 Startup 类如下所示:

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

    ...
}

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

【问题讨论】:

    标签: asp.net-core swagger swashbuckle


    【解决方案1】:

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

    选项 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找到

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多