1、Swagger的作用是什么?
一句话来概述就是,swagger可以将程序中的注释转换成一个web页面展示的文档,如果想知道具体内容,请百度。
2、swagger在.NetCore中如何配置
(1)首先需要引入nuget包,具体需要的包有
Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.SwaggerGen
(2)在Startup.cs中的ConfigureServices里配置下面代码:
services.AddSwaggerGen(action =>
{
action.SwaggerDoc("项目名称", new Info
{
Title = "",//项目名称
Version = "V1.0.0.0",//版本号
Description = "",//项目书说明
TermsOfService = "None",
Contact = new Contact()
{
Name = "",
Email = "",
Url = ""
}
});
// 注释文件路径(注释文件生成:项目属性->生成:输出 勾选"XML文档文件")
var xmlPath = Path.Combine(AppContext.BaseDirectory, "xxxx.xml");//xxxx.xml在配置完swagger之后,重新生成解决
// 关联注释文件
action.IncludeXmlComments(xmlPath);
action.EnableAnnotations();
});
//避免不同命名空间下的相同类名的冲突
services.ConfigureSwaggerGen(options => options.CustomSchemaIds(x => x.FullName));
(3)在Startup.cs中的Configure里配置下面代码:
var apolloEnvironment = Configuration["apollo:Env"];//获取环境
if (apolloEnvironment.Equals("Dev", StringComparison.InvariantCultureIgnoreCase) ||
apolloEnvironment.Equals("Development", StringComparison.InvariantCultureIgnoreCase) ||
apolloEnvironment.Equals("Test", StringComparison.InvariantCultureIgnoreCase))
{
app.UseDeveloperExceptionPage();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
//路由模板
c.RouteTemplate = "{documentName}/swagger.json";
});
//Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("项目根目录下swagger.json文件路径", "项目名称");
});
}
(4)运行项目,在地址后面加上swagger/index.html即可查看