ASP.NET Core WebApi使用Swagger

先在项目中引用Nuget包

Install-Package Swashbuckle.AspNetCore

 

安装之后需要在Startup.cs文件加入如下代码

        public void ConfigureServices(IServiceCollection services)
        {
            //...
            services.AddSwaggerGen(c =>
                       {
                           c.SwaggerDoc("v1", new Info { Title = "Demo", Version = "v1" });
                           var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                           var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                           c.IncludeXmlComments(xmlPath);
                       });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //...
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Demo API");
            });
        }

 

最后在项目属性->生成->输出中勾选XML文档文件

 

运行项目时可在项目端口后加上/swagger就可以查看文档页面了,如下

 

posted @ 2019-06-24 14:33  听雨的人  阅读(273)  评论(0编辑  收藏  举报