一、创建一个Asp.NetCore WebApi 项目
二、引入NuGet包 SwashBuckle.AspNetCore
三、在项目属性配置中设置
四、修改项目的启动文件Startup.cs
1)、在ConfigureServices方法中注册Swagger中间件
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(sg=>{
sg.SwaggerDoc("v1", new Info()
{
Version="1.0.0",
Title="WebApi",
Description = "WebApi接口说明文档",
TermsOfService = "None",
Contact = new Contact
{
Name = "你是我的四月天",
Email = "993484167@qq.com",
Url = "https://www.cnblogs.com/awaTangjay/"
}
});
sg.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebApi.xml"));//WebApi.xml是在项目属性配置中配置的xml文件名
});
}
2)、在Configure方法启用Swagger中间件
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(); app.UseSwagger(s => s.RouteTemplate="swagger/{documentName}/swagger.json");
app.UseSwaggerUI(s => { s.SwaggerEndpoint("v1/swagger.json","v1.0.0"); });//这个v1对应SwaggerDoc中的name v1
}
五、给控制器前加上路由
[Route("api/[controller]/[Action]")]
[ApiController]
public class ValuesController : ControllerBase
{
六、ctrl+F5 调试WebApi
在域名后面输入swagger 回车