C# ASP.NET Core 6 使用 Swashbuckle 產生 OpenAPI 3.0 文件 (Swagger UI) 教學

Swashbuckle 的 Swagger UI 說明對應表 在上一篇 C# ASP.NET Core 6 使用 Swashbuckle 自動產生 OpenAPI 3.0 文件 (Swagger UI) 啟用教學 加入 Swashbuckle 套件和設定完 Swagger UI 資訊後,接下來就是要將 API 呈現出來了。

無法開啟 Swagger 的解決方式

Swashbuckle 只要有任何一個 Action 上面沒有明確的定義 Http 方法(如: HttpGet),Swagger UI 會無法開啟

可以找到類似下面的錯誤:
    
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Ambiguous HTTP method for action - WebApplicationSwaggerTest.Controllers.RuyutController.Test (WebApplicat
ionSwaggerTest). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
         at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
         at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
         at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath)
         at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    

會提示無法找到明確定義的 Controller 和 Action,只要找到並補上就可以了!

不顯示在 Swagger UI 上

若有某些 Action 或是整個 Controller 都不想要出現,可以附加下面的屬性(Attribute) 來忽略:
     
[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
public ActionResult Get()
{
    return Ok();
}
    

自訂不同狀態碼的回應格式

    
    /// <summary>
    /// 傳輸資料的物件
    /// </summary>
    /// <param name="Code">代號</param>
    /// <param name="Name">名稱</param>
    public record DataDto(string Code, string Name);


    [ProducesResponseType(typeof(IList<DataDto>), 200)]
    [ProducesResponseType(typeof(string), 400)]
    [ProducesResponseType(typeof(void), 401)]
    [HttpGet]
    public ActionResult Get()
    {
        return Ok();
    }

    


若加上 XML 註解後則可以自訂各回應要顯示的訊息
    

    /// <summary>
    /// Get API
    /// </summary>
    /// <response code="200">成功,回應資料清單</response>
    /// <response code="400">錯誤</response>
    /// <response code="401">沒有權限</response>
    [ProducesResponseType(typeof(IList<DataDto>), 200)]
    [ProducesResponseType(typeof(string), 400)]
    [ProducesResponseType(typeof(void), 401)]
    [HttpGet]
    public ActionResult Get()
    {
        return Ok();
    }

    


留言