1.新建netcore web api项目
2.安装下列3个NuGet package
3.在startup.cs的ConfigureServices方法里用AddSwaggerGen来添加服务
在Configure里加上UseSwagger和UseSwaggerUI
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);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("MyApi", new OpenApiInfo
{
Title = "Title1",
Description = "Description1",
Version = "Version1",
TermsOfService = new Uri("https://xxxx"),
Contact = new OpenApiContact
{
Name = "lin",
Email = "[email protected]"
},
License = new OpenApiLicense
{
Name = "License",
Url = new Uri("https://xxxxLicense")
}
});
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//此路径要与项目属性中 设置的输出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();
app.UseSwagger(c => c.RouteTemplate = "{documentName}/swagger.json");
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/MyApi/swagger.json", "MyApi");
//这些是ui显示的一些设置
c.DefaultModelsExpandDepth(-1);
c.DisplayRequestDuration();
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
});
}
}
4.打开项目属性,在输出=>xml文档文件位置写上相对路径(此路径和代码c.IncludeXmlComments(xmlPath)里的xmlPath要保持一致)
5.(可选)可以在里输入示例的json,也会显示在swagger ui中
6.启动项目,在端口后输入 swagger就可以访问swagger ui
swagger ui的url为 https://localhost:44323/swagger/index.html
结果如图