NetCore Swagger

//配置swagger
services.AddSwaggerGen(m =>
{

  //生成单个版本

  m.SwaggerDoc("SWG1", new OpenApiInfo { Title = "swaggerTest", Version = "SWG1" });

  //生成多个版本控制接口

  //要启用swagger版本控制要在api控制器或者方法上添加特性[ApiExplorerSettings(GroupName = "v1")] v1是版本号 ApiVersions为版本的枚举

       typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
       {
          m.SwaggerDoc(version, new OpenApiInfo()
           {
                 Title = $"{version}:接口API",
                 Version = version,
                 Description = $"通用版本的CoreApi版本{version}"
           });
       });

  //添加读取注释服务
  var basePath = Path.GetDirectoryName(typeof(BaseController).Assembly.Location);
  if (string.IsNullOrEmpty(basePath))
  {
    basePath = PlatformServices.Default.Application.ApplicationBasePath;
  }
  var xmlPath = Path.Combine(basePath, "XX.API.xml");
  m.IncludeXmlComments(xmlPath, true);//添加控制器层注释(true表示显示控制器注释)
  var xmlModelPath = Path.Combine(basePath, "XX.Model.xml");//这个就是Model层的xml文件名

  //注意,如果你的Model与API不在一个类库,需要将你涉及到的实体库都开启生成xml文档
  m.IncludeXmlComments(xmlModelPath, true);

  

 

 

  //m.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序
  m.EnableAnnotations();

  //添加身份认证
  m.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  {
  Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
  Name = "Authorization",
  In = ParameterLocation.Header,
  Type = SecuritySchemeType.ApiKey,
  BearerFormat = "JWT",
  Scheme = "Bearer"
  });
  m.AddSecurityRequirement(new OpenApiSecurityRequirement{
  { new OpenApiSecurityScheme{
  Reference=new OpenApiReference{ Type=ReferenceType.SecurityScheme,Id="Bearer"}
  } ,Array.Empty<string>() }
  });

})

 

//启用swagger
app.UseSwagger();

//生成单个版本
app.UseSwaggerUI(m =>
{
m.SwaggerEndpoint("/Swagger/SWG1/swagger.json", "swaggerTest");
//m.DocExpansion(DocExpansion.None);//折叠swagger中的所有方法
});

//生成多个版本控制接口

app.UseSwaggerUI(c =>
{
  //遍历多版本基本上先不用有需求时打开
  typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
  {
    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");
  });
});

 

按模块分组参考地址: https://www.cnblogs.com/caijt/p/10739841.html

posted @ 2022-02-14 14:45  blsegirl  阅读(74)  评论(0编辑  收藏  举报