C# ASP.NET Core 安裝 Swashbuckle 套件後出現錯誤 解決方式

專案要使用 Swagger UI,在加入 Swashbuckle.AspNetCore 套件並設定完成後出現下列錯誤:
    
An unhandled exception occurred while processing the request.
SwaggerGeneratorException: Ambiguous HTTP method for action - WebApplication1.Controllers.Api.UserController.GetUsers (WebApplication1). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0

Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)

    Stack Query Cookies Headers Routing 

    SwaggerGeneratorException: Ambiguous HTTP method for action - WebApplication1.Controllers.Api.UserController.GetUsers (WebApplication1). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
        Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)
        Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)
        Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwaggerDocumentWithoutFilters(string documentName, string host, string basePath)
        Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwaggerAsync(string documentName, string host, string basePath)
        Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
        Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    

研究了一下後發現是 Swagger/OpenAPI 3.0 要求所有 Action 必須要綁定 HttpMethod 的屬性 (Attribute) ,例如 HttpGet, HttpPost, HttpPut, HttpDelete 等等,

以上面的錯誤訊息看起來是 UserController.cs 下的 GetUsers 沒有綁定,依照平時使用的 HttpMethod 增加對應的屬性後 (筆者這裡就是加上 [HttpGet])就成功解決問題了

留言