ASP.NET Core – Swagger

前言

Swagger (OpenAPI) 是一套 Web API 文档规范. 

ASP.NET Core 有 2 个 Library 可以帮我们从 Web API Controller convert to 文档哦

一个是 Swashbuckle

另一个是 NSwag

NSwag 还能直接生产 client code 比如 typescript 等等哦. 但我是没有这个需求啦, 所以我用 Swashbuckle

 

主要参考

Get started with Swashbuckle and ASP.NET Core

Controller action return types in ASP.NET Core web API

 

安装 nuget

dotnet add package Swashbuckle.AspNetCore

 ASP.NET Core 6.0 模板已经有自带的了.

ASP.NET Core – Swagger

跑起来长这样

ASP.NET Core – Swagger

 

 

配置 docs

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1.0", new OpenApiInfo
    {
        Title = "Project Web API",
        Version = "v1.0",
        Description = "Project Web API version 1.0",
        Contact = new OpenApiContact
        {
            Name = "Derrick Yam",
            Email = "hengkeat87@gmail.com",
        },
    });
});

UI Endpoint

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Project Web API v1.0");
    options.DocExpansion(DocExpansion.None);
});

 

开启 XML comments

打开 project.csproj, 添加 2 行, Nowarn 是去掉警告, 不然很烦.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

 

上一篇:Spring Boot之Swagger 3.0


下一篇:Spring Swagger