1.从“管理 NuGet 程序包”对话框中
1)在搜索框中输入“Swashbuckle.AspNetCore”
2)从“浏览”选项卡中选择“Swashbuckle.AspNetCore”包,然后单击“安装”
2.添加并配置 Swagger 中间件
首先引入命名空间:
using Swashbuckle.AspNetCore.Swagger;
创建一个SwaggerExtensions类:
public static class SwaggerExtensions
{
public static void AddSwagger(this IServiceCollection services)
{
var ApiName = "Webapi.Core";
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("V1", new OpenApiInfo
{
// {ApiName} 定义成全局变量,方便修改
Version = "V1",
Title = $"{ApiName} 接口文档——Netcore 3.0",
Description = $"{ApiName} HTTP API V1",
});
c.OrderActionsBy(o => o.RelativePath);
});
}
}
将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwagger();
services.AddControllers();
}
在 Startup.Configure
方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}//Swagger
app.UseSwagger();
app.UseSwaggerUI(c=> {
c.SwaggerEndpoint("/swagger/V1/swagger.json", "WebApi.Core V1");c.RoutePrefix = "";
});
app.UseHttpsRedirection();
app.UseRouting();app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
启动应用,并导航到 http://localhost:<port>/swagger/v1/swagger.json
。 生成的描述终结点的文档显示如下json格式。
可在 http://localhost:<port>/swagger
找到 Swagger UI。 通过 Swagger UI 浏览 API文档,如下所示
要在应用的根 (http://localhost:<port>/
) 处提供 Swagger UI,请将 RoutePrefix
属性设置为空字符串:
app.UseSwaggerUI(
c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty; }
);
如果接就想直接访问:http://localhost:5000/index.html
需要修改