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
結果如圖