1. 程式人生 > >【官檔整理】ASP.NET Core WebAPI 安裝 Swagger(Swashbuckle) 元件

【官檔整理】ASP.NET Core WebAPI 安裝 Swagger(Swashbuckle) 元件

官檔地址:

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1

個人整理:

1、開啟專案文件:屬性-生成-XML文件檔案,debug和release都要配置

成功後.csproj檔案中會出現

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>ProjectName.xml</DocumentationFile>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>ProjectName.xml</DocumentationFile>
  </PropertyGroup>

2、Nuget安裝 Swashbuckle.AspNetCore

3、Startup.ConfigureServices中新增

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("doc", new Info() { Title = "@title" });
                options.IncludeXmlComments("ProjectName.xml");
            });

4、Startup.Configure中新增

            app.UseSwagger();
            app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/doc/swagger.json", null));

5、訪問地址:/swagger/index.html

 

補充-如果還需要除錯時啟動,修改launchSettings.json

{
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:5857/",
            "sslPort": 0
        }
    },
    "profiles": {
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "swagger",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        "ProjectName": {
            "commandName": "Project",
            "launchBrowser": true,
            "launchUrl": "swagger",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "http://localhost:5858/"
        }
    }
}