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:

    • 移至 [檢視] > [其他視窗] > [套件管理員主控台]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

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

  • 匯入下列命名空間:Import the following namespaces:
using NJsonSchema;
using NSwag.AspNetCore;
  • ConfigureServices 方法中,註冊所需的 Swagger 服務:In the ConfigureServices method, register the required Swagger services:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt => 
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc();

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

    // Register the Swagger generator and the Swagger UI middlewares
    app.UseSwagger();
    app.UseSwaggerUi3();

    app.UseMvc();
}
  • 啟動應用程式。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.

  • 啟動 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", "12.0.9.0 (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();
                UpdateJsonSerializerSettings(settings);
                return settings;
            });
        }

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

        // code omitted for brevity

提示

C# 用戶端程式碼會根據 [Settings] (設定) 索引標籤中的選取項目來產生。修改設定以執行工作,例如重新命名預設的命名空間和產生同步方法。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.SwaggerContact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = "https://twitter.com/spboyer"
        };
        document.Info.License = new NSwag.SwaggerLicense
        {
            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:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
  • 以滑鼠右鍵按一下方案總管中的專案,然後選取 [屬性]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:

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

    _context.TodoItems.Add(item);
    _context.SaveChanges();

    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. 使用下列屬性裝飾動作:Decorate the action with the following attributes:

[ProducesResponseType(typeof(TodoItem), 201)]   // Created
[ProducesResponseType(400)]                     // BadRequest

由於 NSwag 會使用反映,而針對 Web API 動作建議使用的傳回型別是 ActionResult<T>,因此它只能推斷 T 所定義的傳回型別。Because 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:

[HttpPost]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    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 is decorated with 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. 使用下列屬性裝飾動作:Decorate the action with the following attributes:

[ProducesResponseType(201)]     // Created
[ProducesResponseType(400)]     // 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, decorate 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.