.net core 添加 Swagger

时间:2022-12-24 17:30:19

1.新建一个Core项目

  添加nuget包:Swashbuckle.AspNetCore

  添加Startup文件:

    先引用:

using Swashbuckle.AspNetCore.Swagger;

    添加的配置如下:

        public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}

  这样就可以打开swagger调试接口了  https://localhost:44399/swagger/index.html

2.swagger显示接口xml注释

  右键属性    生成   输出   XML文档文件  打勾

.net core 添加 Swagger

  配置

        public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "MySwagger.xml");//和项目名对应
c.IncludeXmlComments(xmlPath);
});
}

效果图:

    .net core 添加 Swagger