.NET Core WEB API使用Swagger生成在线接口文档

1项目引用Swashbuckle.AspNetCore程序集和Microsoft.Extensions.PlatformAbstractions程序集

  右击项目打开"管理NuGet程序包...",选择Swashbuckle.AspNetCore进行安装,如下图所示:

  选择选择Microsoft.Extensions.PlatformAbstractions进行安装,如下图所示:

2.在工程中配置Swagger

  在Startup.cs类中的ConfigureServices中添加如下代码:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger示例 API"
                });
                //Determine base path for the application.  
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            });
        }

在Configure方法中添加如下代码:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            //添加Swagger引用
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger示例API V1");
            });
        }

3.Swagger在线接口文档效果

  工程运行后,在服务地址的端口号后面输入swagger/index.html,在线文档的效果就出来了,如下图所示:

4.让方法和字段显示文字注释

  首先右击项目,选择“属性”,让项目输出注释xml文档,如下图所示:

  在ConfigureServices方法中添加如下代码:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger示例 API"
                });
                //显示文档注释
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "SwaggerTest.xml");
                options.IncludeXmlComments(xmlPath);
            });
        }

  给相应的接口方法和实体字段添加注释后,启动项目效果如下所示:

5.把Swagger文档设置为项目的启始页

  打开工程的launchSettings.json配置文件,把"launchUrl": 的地址修改为"swagger/index.html",如下图所示:

猜你喜欢

转载自www.cnblogs.com/fengye310/p/10781040.html