1.安装NuGet包
2.配置
3.运行测试
参考博客:https://www.cnblogs.com/yilezhu/p/9241261.html
一 安装NuGet包
包名:Swashbuckle.AspNetCore
二 配置
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger; namespace WebApplicationCoreAPIStudy4
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // 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_1); ////注册Swagger生成器,定义一个和多个Swagger 文档
//services.AddSwaggerGen(c =>
//{
// c.SwaggerDoc("v1", new Info { Title = "My API_info", Version = "v1_info" });
//}); //注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "yilezhu's API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact
{
Name = "依乐祝",
Email = string.Empty,
Url = "http://www.cnblogs.com/yilezhu/"
},
License = new License
{
Name = "许可证名字",
Url = "http://www.cnblogs.com/yilezhu/"
}
});
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "WebApplicationCoreAPIStudy4.xml");
c.IncludeXmlComments(xmlPath);
}); } // 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();
}
else
{
app.UseHsts();
} app.UseHttpsRedirection();
app.UseMvc(); //启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1_endpoint"); //加上后,访问地址:https://localhost:44389
//c.RoutePrefix = string.Empty;//访问地址:https://localhost:44389/swagger
});
}
}
}