前言:咱們開發了不少的接口後,爲了方便調用人員使用,須要給出接口地址,參數和解釋說明,可能還須要示例。 那麼swagger這個開源項目,已經給咱們提供好了一整套的解決方案:web
本博客參考文檔:json
Swashbuckle 和 ASP.NET Core 入門 api
什麼是 Swagger/OpenAPI?網絡
Swagger 是一個與語言無關的規範,用於描述 REST API。 Swagger 項目已捐贈給 OpenAPI 計劃,如今它被稱爲開放 API。 這兩個名稱可互換使用,但 OpenAPI 是首選。 它容許計算機和人員瞭解服務的功能,而無需直接訪問實現(源代碼、網絡訪問、文檔)。 其中一個目標是儘可能減小鏈接取消關聯的服務所需的工做量。 另外一個目標是減小準確記錄服務所需的時間。(說明參考微軟官方文檔:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-3.0)app
快速添加webapi項目對swagger的支持:visual-studio
1-添加程序包引用:Swashbuckle.AspNetCore -Version 5.0.0-rc4 (該版本目前屬於預覽版,須要勾選預覽版才能夠看到)ui
2-添加並配置 Swagger 中間件:spa
using Microsoft.OpenApi.Models; public void ConfigureServices(IServiceCollection services) { // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // include document file c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); }); services.AddControllers(); }
這裏,須要添加對項目xml文件的引用,默認啓用根目錄下的項目文件名的xml文件,項目xml文件生成配置以下:.net
爲了兼容發佈版本,我們設置了輸出路徑爲空,xml名稱改成:項目名.xml code
3-在 Startup.Configure
方法中,啓用中間件爲生成的 JSON 文檔和 Swagger UI 提供服務:
public void Configure(IApplicationBuilder app) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4-結束,查看效果:
啓動應用,並導航到: http://localhost:<port>/swagger/v1/swagger.json
。 生成的描述終結點的文檔顯示在 Swagger 規範 (swagger.json) 中。
可在 http://localhost:<port>/swagger
找到 Swagger UI。 經過 Swagger UI 瀏覽 API
5-走過的坑1:官網文檔前半部分並無讓添加xml文件的代碼。後面有涉及,不過仍是感受有點亂,本博客已加上!
走過的坑2:常見異常:Ambiguous HTTP method for action - PaymentAccountAPI.Controllers.PayAccountController.GetTransactions (PaymentAccountAPI). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
該異常是由於控制器方法,缺乏方法類型的標記,[HttpGet]、[HttpPost],以下圖:
參考解決方案文檔:Ambiguous HTTP method Actions require an explicit HttpMethod binding for Swagger 2.0
走過的坑3:缺乏xml項目文件異常_500錯誤: 項目部署到IIS後,不會自動把xml文件帶過去,須要咱們收到複製過去,在運行查看效果。
把項目xml文件放入後,再試(須要重啓IIS項目),效果正常: