asp.net core swagger使用及注意事項


 

  Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。是一款RESTFUL接口的文檔在線自動生成+功能測試軟件。主要目的是構建標准的、穩定的、可重用的、交互式的API以及簡單方便的功能測試。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。

 作用:

    1. 根據基於規范的標准設計和建模API

    2. 幾乎可以用任何語言為您的API構建穩定,可重用的代碼

 3. 使用交互式API文檔改善開發人員體驗

 4. 對您的API執行簡單的功能測試,而無需開銷

 5. 在您的API架構中設置和實施API樣式指南

一 、swagger的創建  

1.新建asp.net core項目

2.nuget上安裝Swashbuckle.AspNetCore

Swashbuckle有三個主要組件:

  • Swashbuckle.AspNetCore.Swagger:一個Swagger對象模型和中間件,用於將SwaggerDocument對象公開為JSON端點。

  • Swashbuckle.AspNetCore.SwaggerGen:一個Swagger生成器,可SwaggerDocument直接從路由,控制器和模型構建對象。它通常與Swagger端點中間件結合使用,以自動顯示Swagger JSON。

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI工具的嵌入式版本。它解釋了Swagger JSON,以便為描述Web API功能構建豐富,可定制的體驗。它包括用於公共方法的內置測試工具。

3.在Startup的 ConfigureServices配置服務中添加中間件

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });
        }

4.在Startup的 Configure配置服務中啟用中間件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger(); app.UseSwaggerUI(c => { c.InjectJavascript(""); c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
        }

5.啟動程序,然后鍵入url  swagger/index.html或者swagger

 

 

6.修改Web API項目首頁重定向

在 Properties >> launchSettings.json文件中更改默認配置 >> 啟用 "launchUrl": "swagger"配置

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:49833",
      "sslPort": 44387
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SwaggerTest": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:49833/swagger",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

 

7.為控制器中每個方法添加注釋啟用XML注釋為未記錄的公共類型和成員提供調試信息     項目 >> 屬性 >> 生成

 

修改Startup的 ConfigureServices配置服務

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                //添加xml文件
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath);
            });
        }

 

 

 8.添加控制器,啟動  創建成功

 

二 、注意事項

1.啟動后出現 No operations defined in spec! 問題

在查看/swagger/v1/swagger.json文件后發現是沒有配置parh

打開后內容是:

{"swagger":"2.0","info":{"version":"v1","title":"My API"},"paths":{},"definitions":{}}

 

 

解決:該項目中未添加API控制器,注意必須是API控制器,並且需要在處理方法上添加HTTP標記

/// <summary>
        /// Delete
        /// </summary>
        /// <param name="ids">刪除id列表</param>
        /// <returns>被成功刪除id列表</returns>
        [HttpDelete]
        public ActionResult<IEnumerable<string>> Delete(params string[] ids)
        {
            if (ids == null)
                return NoContent();
            return ids;
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="id">Update id</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update(string id)
        {
            return Content("Update id:" + id);
        }

        /// <summary>
        /// Add
        /// </summary>
        /// <param name="param">Add ids</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(params string[] param)
        {
            return Content(string.Join(",", param));
        }

2.啟動后出現  Failed to load API definition.  錯誤 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace SwaggerTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        /// <summary>
        /// Delete /// </summary>
        /// <param name="ids">刪除id列表</param>
        /// <returns>被成功刪除id列表</returns>
        //[HttpDelete]
        public ActionResult<IEnumerable<string>> Delete(params string[] ids) { if (ids == null) return NoContent(); return ids; } /// <summary>
        /// Update
        /// </summary>
        /// <param name="id">Update id</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update(string id)
        {
            return Content("Update id:" + id);
        }

        /// <summary>
        /// Add
        /// </summary>
        /// <param name="param">Add ids</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(params string[] param)
        {
            return Content(string.Join(",", param));
        }
    }
}

 

原因:控制器中出現未被HTTP標記的方法

解決方案:刪除該方法或者添加相應的HTTP標記

 

 

官網文檔:https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=netcore-cli#add-and-configure-swagger-middleware

更多請參考swagger官網:https://swagger.io/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM