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", 如下图所示:
来源: http://www.bubuko.com/infodetail-3038708.html