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