NSwag 與 ASP.NET Core 使用者入門Get started with NSwag and ASP.NET Core

作者:Christoph NienaberRico SuterDave BrockBy Christoph Nienaber, Rico Suter, and Dave Brock

NSwag 提供下列功能:NSwag offers the following capabilities:

  • 能夠運用 Swagger UI 和 Swagger 產生器。The ability to utilize the Swagger UI and Swagger generator.
  • 彈性的程式碼產生功能。Flexible code generation capabilities.

使用 NSwag 時,您不需要有現有的 API — 您可以使用包含 Swagger 的協力廠商 API,然後產生用戶端實作。With NSwag, you don't need an existing API—you can use third-party APIs that incorporate Swagger and generate a client implementation. NSwag 可讓您加速開發週期,並輕鬆地因應 API 變更進行調整。NSwag allows you to expedite the development cycle and easily adapt to API changes.

註冊 NSwag 中介軟體Register the NSwag middleware

註冊 NSwag 中介軟體來:Register the NSwag middleware to:

  • 為實作的 Web API 產生 Swagger 規格。Generate the Swagger specification for the implemented web API.
  • 提供 Swagger UI 以瀏覽並測試 Web API。Serve the Swagger UI to browse and test the web API.

若要使用 NSwag ASP.NET Core 中介軟體,請安裝 NSwag.AspNetCore NuGet 套件。To use the NSwag ASP.NET Core middleware, install the NSwag.AspNetCore NuGet package. 此套件包含用以產生並提供 Swagger 規格、Swagger UI (v2 和 v3) 及 ReDoc UI 的中介軟體。This package contains the middleware to generate and serve the Swagger specification, Swagger UI (v2 and v3), and ReDoc UI.

請使用下列其中一種方法來安裝 NSwag NuGet 套件:Use one of the following approaches to install the NSwag NuGet package:

  • 從 [套件管理員主控台]**** 視窗中:From the Package Manager Console window:

    • 移至 [查看 > 其他 Windows > 封裝管理員主控台]Go to View > Other Windows > Package Manager Console

    • 巡覽至 TodoApi.csproj 檔案所在目錄Navigate to the directory in which the TodoApi.csproj file exists

    • 執行以下命令:Execute the following command:

      Install-Package NSwag.AspNetCore
  • 從 [管理 NuGet 套件]**** 對話方塊中:From the Manage NuGet Packages dialog:

    • 方案總管 > 管理 NuGet 套件] 中的專案上按一下滑鼠右鍵Right-click the project in Solution Explorer > Manage NuGet Packages
    • 將 [套件來源]**** 設定為 "nuget.org"Set the Package source to "nuget.org"
    • 在搜尋方塊中輸入 "NSwag.AspNetCore"Enter "NSwag.AspNetCore" in the search box
    • 從 [瀏覽]**** 索引標籤中選取 "NSwag.AspNetCore" 套件,並按一下 [安裝]****Select the "NSwag.AspNetCore" package from the Browse tab and click Install

新增和設定 Swagger 中介軟體Add and configure Swagger middleware

請執行下列步驟,以在您的 ASP.NET Core 應用程式中新增及設定 Swagger:Add and configure Swagger in your ASP.NET Core app by performing the following steps:

  • Startup.ConfigureServices 方法中,註冊所需的 Swagger 服務:In the Startup.ConfigureServices method, register the required Swagger services:
public void ConfigureServices(IServiceCollection services)
    services.AddDbContext<TodoContext>(opt =>

    // Register the Swagger services
  • Startup.Configure 方法中,啟用中介軟體為產生的 Swagger 規格和 SwaggerUI 提供服務:In the Startup.Configure method, enable the middleware for serving the generated Swagger specification and the Swagger UI:
public void Configure(IApplicationBuilder app)

    // Register the Swagger generator and the Swagger UI middlewares

  • 啟動應用程式。Launch the app. 瀏覽至:Navigate to:
    • http://localhost:<port>/swagger 以檢視 Swagger UI。http://localhost:<port>/swagger to view the Swagger UI.
    • http://localhost:<port>/swagger/v1/swagger.json 以檢視 Swagger 規格。http://localhost:<port>/swagger/v1/swagger.json to view the Swagger specification.

程式碼產生Code generation

您可以選擇下列其中一個選項來利用 NSwag 的程式碼產生功能:You can take advantage of NSwag's code generation capabilities by choosing one of the following options:

使用 NSwagStudio 來產生程式碼Generate code with NSwagStudio

  • 依照 NSwagStudio GitHub 存放庫 (英文) 的指示來安裝 NSwagStudio。Install NSwagStudio by following the instructions at the NSwagStudio GitHub repository. 在 [NSwag 發行] 頁面上,您可以下載不需要安裝和系統管理員許可權即可啟動的 xcopy 版本。On the NSwag release page you can download an xcopy version which can be started without installation and admin privileges.

  • 啟動 NSwagStudio,然後在 [Swagger Specification URL] (Swagger 規格 URL)**** 文字方塊中輸入 swagger.json 檔案 URL。Launch NSwagStudio and enter the swagger.json file URL in the Swagger Specification URL text box. 例如: http://localhost:44354/swagger/v1/swagger.jsonFor example, http://localhost:44354/swagger/v1/swagger.json.

  • 按一下 [Create local Copy] (建立本機複本)**** 按鈕,以產生 Swagger 規格的 JSON 表示法。Click the Create local Copy button to generate a JSON representation of your Swagger specification.

    建立 Swagger 規格的本機複本

  • 在 [Outputs] (輸出)**** 區域中,按一下 [CSharp Client] (CSharp 用戶端)**** 核取方塊。In the Outputs area, click the CSharp Client check box. 視您的專案而定,您也可以選擇 [TypeScript Client] (TypeScript 用戶端)**** 或 [CSharp Web API Controller] (CSharp Web API 控制器)****。Depending on your project, you can also choose TypeScript Client or CSharp Web API Controller. 如果您選取 [CSharp Web API Controller] (CSharp Web API 控制器)****,服務規格會重建服務,作為反向產生。If you select CSharp Web API Controller, a service specification rebuilds the service, serving as a reverse generation.

  • 按一下 [Generate Outputs] (產生輸出)****,以產生 TodoApi.NSwag 專案 的完整 C# 用戶端實作。Click Generate Outputs to produce a complete C# client implementation of the TodoApi.NSwag project. 若要查看所產生的用戶端程式碼,請按一下 [CSharp Client] (CSharp 用戶端)**** 索引標籤:To see the generated client code, click the CSharp Client tab:

// <auto-generated>
//     Generated using the NSwag toolchain v12.0.9.0 (NJsonSchema v9.13.10.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org)
// </auto-generated>

namespace MyNamespace
    #pragma warning disable

    [System.CodeDom.Compiler.GeneratedCode("NSwag", " (NJsonSchema v9.13.10.0 (Newtonsoft.Json v11.0.0.0))")]
    public partial class TodoClient
        private string _baseUrl = "https://localhost:44354";
        private System.Net.Http.HttpClient _httpClient;
        private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;

        public TodoClient(System.Net.Http.HttpClient httpClient)
            _httpClient = httpClient;
            _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() =>
                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                return settings;

        public string BaseUrl
            get { return _baseUrl; }
            set { _baseUrl = value; }

        // code omitted for brevity


C # 用戶端程式代碼會根據 [ 設定 ] 索引標籤中的選取專案來產生。請修改設定來執行工作,例如預設命名空間重新命名和同步方法產生。The C# client code is generated based on selections in the Settings tab. Modify the settings to perform tasks such as default namespace renaming and synchronous method generation.

  • 將產生的 C# 程式碼複製到將取用 API 的用戶端專案中檔案。Copy the generated C# code into a file in the client project that will consume the API.
  • 開始取用 Web API:Start consuming the web API:
 var todoClient = new TodoClient();

// Gets all to-dos from the API
 var allTodos = await todoClient.GetAllAsync();

 // Create a new TodoItem, and save it via the API.
var createdTodo = await todoClient.CreateAsync(new TodoItem());

// Get a single to-do by ID
var foundTodo = await todoClient.GetByIdAsync(1);

自訂 API 文件Customize API documentation

Swagger 提供選項來記錄物件模型,以簡化 Web API 的取用作業。Swagger provides options for documenting the object model to ease consumption of the web API.

API 資訊與描述API info and description

Startup.ConfigureServices 方法中,傳遞至 AddSwaggerDocument 方法的組態動作會新增作者、授權和描述等資訊:In the Startup.ConfigureServices method, a configuration action passed to the AddSwaggerDocument method adds information such as the author, license, and description:

services.AddSwaggerDocument(config =>
    config.PostProcess = document =>
        document.Info.Version = "v1";
        document.Info.Title = "ToDo API";
        document.Info.Description = "A simple ASP.NET Core web API";
        document.Info.TermsOfService = "None";
        document.Info.Contact = new NSwag.OpenApiContact
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = "https://twitter.com/spboyer"
        document.Info.License = new NSwag.OpenApiLicense
            Name = "Use under LICX",
            Url = "https://example.com/license"

Swagger UI 會顯示版本資訊:The Swagger UI displays the version's information:

含有版本資訊的 Swagger UI

XML 註解XML comments

若要啟用 XML 註解,請執行下列步驟:To enable XML comments, perform the following steps:

  • 以滑鼠右鍵按一下 [方案總管]**** 中的專案,然後選取 [編輯 <專案名稱>.csproj]****。Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
  • 將醒目提示的程式碼行手動新增至 .csproj 檔案:Manually add the highlighted lines to the .csproj file:
  • 以滑鼠右鍵按一下方案總管**** 中的專案,然後選取 [屬性]****Right-click the project in Solution Explorer and select Properties
  • 核取 [組建] 索引標籤之 [輸出] 區段底下的 [ XML 檔檔案] 方塊Check the XML documentation file box under the Output section of the Build tab

資料註解Data annotations

由於 NSwag 會使用反映,而針對 Web API 動作建議使用的傳回型別是 IActionResult,因此它無法推斷您動作的執行內容和傳回內容。Because NSwag uses Reflection, and the recommended return type for web API actions is IActionResult, it can't infer what your action is doing and what it returns.

請考慮下列範例:Consider the following example:

public IActionResult Create([FromBody] TodoItem item)
    if (item == null)
        return BadRequest();


    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);

上述動作會傳回 IActionResult,但在動作內部則會傳回 CreatedAtRouteBadRequestThe preceding action returns IActionResult, but inside the action it's returning either CreatedAtRoute or BadRequest. 請使用資料註解來告知用戶端已知此動作要傳回哪些 HTTP 狀態碼。Use data annotations to tell clients which HTTP status codes this action is known to return. 以下列屬性標示動作:Mark the action with the following attributes:

[ProducesResponseType(typeof(TodoItem), StatusCodes.Status201Created)]  // Created
[ProducesResponseType(StatusCodes.Status400BadRequest)]                 // BadRequest

由於 NSwag 會使用反映,而 web API 動作的建議傳回型別是 <T> ActionResult,因此它只能推斷所定義的傳回型別 TBecause NSwag uses Reflection, and the recommended return type for web API actions is ActionResult<T>, it can only infer the return type defined by T. 您無法自動推斷其他可能的傳回型別。You can't automatically infer other possible return types.

請考慮下列範例:Consider the following example:

public ActionResult<TodoItem> Create(TodoItem item)

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);

上述動作會傳回 ActionResult<T>The preceding action returns ActionResult<T>. 在動作內部則會傳回 CreatedAtRouteInside the action, it's returning CreatedAtRoute. 由於控制器具有 [ApiController] 屬性,因此也可能 BadRequest 回應。Since the controller has the [ApiController] attribute, a BadRequest response is possible, too. 如需詳細資訊,請參閱自動 HTTP 400 回應For more information, see Automatic HTTP 400 responses. 請使用資料註解來告知用戶端已知此動作要傳回哪些 HTTP 狀態碼。Use data annotations to tell clients which HTTP status codes this action is known to return. 以下列屬性標示動作:Mark the action with the following attributes:

[ProducesResponseType(StatusCodes.Status201Created)]     // Created
[ProducesResponseType(StatusCodes.Status400BadRequest)]  // BadRequest

在 ASP.NET Core 2.2 或更新版本中,您可以使用慣例,而不使用 [ProducesResponseType] 來明確地裝飾個別動作。In ASP.NET Core 2.2 or later, you can use conventions instead of explicitly decorating individual actions with [ProducesResponseType]. 如需詳細資訊,請參閱使用 Web API 慣例For more information, see 使用 Web API 慣例.

Swagger 產生器現在可以正確描述此動作,而產生的用戶端會知道呼叫端點時它們所接收的內容。The Swagger generator can now accurately describe this action, and generated clients know what they receive when calling the endpoint. 建議您以這些屬性標記所有動作。As a recommendation, mark all actions with these attributes.

如需 API 動作應該傳回哪些 HTTP 回應的指導方針,請參閱 RFC 7231 規格For guidelines on what HTTP responses your API actions should return, see the RFC 7231 specification.