Asp.net-Core

Asp.Net core Swashbuckle 設置 operationId

  • March 3, 2022

如何operationId在 Asp.Net Core 2.1 項目中設置 swagger 屬性?根據這篇文章我應該使用SwaggerOperationAttribute但我在 Swashbuckle.AspNetCore 庫中找不到它。還有一個IOperationFilter

public interface IOperationFilter
{
   void Apply(Operation operation, OperationFilterContext context);
}

而且我找不到任何用於大搖大擺的實現。

還有其他 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" });
});

這將按照ControllerName_HttpMethod約定將 operationIds 添加到您的所有方法中。

選項 2:基於 ActionFilter/Attribute - 您可以配置每個 Action 方法(就像您對操作過濾器所做的那樣,只需向 HTTP 動詞操作過濾器SwaggerOperation添加一個屬性,如下所示:Name

[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

引用自:https://stackoverflow.com/questions/52262826