net5集成swagger
net5集成swagger
1、新建站点,net5版本
2、通过nuget引用Swashbuckle.AspNetCore
3、添加自定义类
/// <summary> /// swagger /// </summary> public static class SwaggerExtension { public static void AddSwaggerInfo(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); var ApiName = "mytestapi"; services.AddSwaggerGen(c => { c.SwaggerDoc("V1", new OpenApiInfo { Version = "V1", Title = $"{ApiName} 接口文档——mytestapi", Description = $"{ApiName} HTTP API V1", }); c.OrderActionsBy(o => o.RelativePath); var security = new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "my-token-key", Type = ReferenceType.SecurityScheme } }, Array.Empty<string>() } }; c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。 c.AddSecurityDefinition("my-token-key", new OpenApiSecurityScheme { Description = "JWT", Name = "mytokenkey", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); // 获取xml var xmlPath = Path.Combine(AppContext.BaseDirectory, "mytestapi.xml"); var mxmlPath = Path.Combine(AppContext.BaseDirectory, "mytestapimodel.xml"); c.IncludeXmlComments(xmlPath, true); c.IncludeXmlComments(mxmlPath); }); } }
4、在ConfigServices中引用
services.AddSwaggerInfo();
5、在Config中增加:
app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint($"/swagger/V1/swagger.json", "mytestapi V1"); c.RoutePrefix = “”;//前缀 c.DefaultModelsExpandDepth(0); });
6、最后记得选择生成xml文件
运行效果:
路径为站点路径,带上/index.html。如果有前缀的,则带上/前缀/index.html