Skip to content
欢迎扫码关注公众号

.NET Core 使用 Swagger

  1. 使用 NuGet 安装 Swashbuckle.AspNetCore

    bash
    Install-Package Swashbuckle.AspNetCore
  2. 修改 Startup.cs 文件

    cs
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
            {
                Version = "v1",
                Title = "My API",
                Description = "by JiaJia"
            });
        });
    }
    
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseMvc();
    
    #if DEBUG
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            // c.DocExpansion(DocExpansion.None);
        });
    #endif
    }
  3. 访问 Swagger UI 地址 http://localhost:56099/swagger/

  4. 显示方法备注。

    现在的 Swagger UI 只会显示接口名,但没有显示备注。如需显示备注,需要

    1. 在项目属性的 生成 => 输出 中勾选 XML 文档文件

      如: bin\Debug\netcoreapp2.1\Octopus.Cloud.User.xml

    2. Start.cs => ConfigureServices 方法中的 AddSwaggerGen 处增加 IncludeXmlComments 处理。

      cs
      services.AddSwaggerGen(options =>
      {
          options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
          {
              Version = "v1",
              Title = "Octopus Cloud API",
              Description = "by Octopus"
          });
      
          options.IncludeXmlComments(string.Format("{0}/Octopus.Cloud.User.xml",
              AppDomain.CurrentDomain.BaseDirectory));
      });
    3. 重启之后就可以看到接口方法对应的备注了。

      cs
      /// <summary>
      /// 根据 ID 获取用户信息
      /// </summary>
      /// <param name="id">用户 ID</param>
      /// <returns>用户信息</returns>
      [HttpGet("{id}")]
      public ActionResult<string> Get(int id)
      {
          return "user info";
      }

  1. Swashbuckle.AspNetCore 项目 URL:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
  2. webapi 文档描述-swagger

记一个奇怪的 404 错误

在一个误操作之后,使用 IISExpress 启动后,再打开 Swagger UI 的地址会显示 404 错误;但是使用 WebApplication2 启动是可以打开的。

这个误操作是这样的:本来是想设置启动工程直接打开 swagger 页,所以在【工程属性 => 调试】中修改设置,应该是修改【启动浏览器】的值,但我第一次修改时误修改了【Web 服务器设置 => 应用 URL】的值(将 http://localhost:56100/ 改成了 http://localhost:56100/swagger/),启动后发现不对,就又改了回去。之后再访问 http://localhost:56100/swagger/ 就会显示 404 错误。

本以为是 appsettings.json 或者 launchSettings.json 中的设置不对导致的,但是对比了下发现并没有改动。

最后在工程目录的 .vs\config\applicationhost.config 文件中发现了增加了一段配置(下面代码中的 path="/swagger" 部分),将这部分删除后,一切就都正常了。

xml
<configuration>
  <system.applicationHost>
    <sites>
      <site name="WebApplication2" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\liujiajia\source\repos\WebApplication2\WebApplication2" />
        </application>
        <application path="/swagger" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\liujiajia\source\repos\WebApplication2\WebApplication2" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation="*:56100:localhost" />
        </bindings>
      </site>
    </sites>
  </system.applicationHost>
</configuration>

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.