首先安装NuGet包 Swashbuckle.AspNetCore
紧接着 Startup 的代码
using Swashbuckle.AspNetCore.SwaggerUI;//要添加的命名空间
namespace Project.API
{
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.AddControllers();
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new OpenApiInfo() { Title = "项目名称 Api", Version = "v1" });//项目名称填你的项目名称,下同
config.CustomSchemaIds(type => type.FullName);
config.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}/Project.API.xml");//Project.API 为你的项目名称
});
Register(services);
services.AddOptions();
}
/// <summary>
/// 依赖注入
/// </summary>
/// <param name="services"></param>
private static void Register(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSwagger(c =>
{
c.RouteTemplate = "api-doc/{documentName}/swagger.json";//配置后,你的最终访问路径就就是 /api-doc/index.html
});
app.UseSwaggerUI(c =>
{
c.InjectJavascript("/zh_CN.js");//中文包,怎么测试也出不来,等待一个大佬解决下,所以这里就不放中文包了,因为根本用不了,(这句可以删
c.ShowExtensions();
c.DocExpansion(DocExpansion.None);
c.RoutePrefix = "api-doc";
c.SwaggerEndpoint("v1/swagger.json", "项目名称 Api v1");
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=ApiHome}/{action=Index}/{id?}");
});
}
}
}
最后两步
你的项目-->右键属性-->生成事件-->生成后事件命令行--> copy $(TargetDir){项目名称}.xml $(ProjectDir){项目名称}.xml
你的项目-->右键属性-->生成事件-->生成后事件命令行--> 输出 如图所示
最后运行试试
记得切换端口号 https://localhost:{xxxx}/api-doc/index.html