安装对应包
using Microsoft.AspNetCore.Mvc.Controllers using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using IGeekFan.AspNetCore.Knife4jUI;
Startup中对应修改
ConfigureServices中
// 添加swagger api docs services.AddSwaggerGen(sw => { //sw.OperationFilter<AddAuthTokenHeaderParameter>(); //sw.SwaggerDoc("v1", new OpenApiInfo { Title = "API V1", Version = "v1" }); sw.SwaggerDoc("v1", new OpenApiInfo { Title = "AAA Api", Description = "ASP.NET Core Web API", Version = "v1" }); var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.xml").ToList(); foreach (var item in files) { sw.IncludeXmlComments(item, true); } sw.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: "Authorization: Bearer {token}"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); sw.CustomOperationIds(apiDesc => { var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor; return controllerAction.ControllerName + "-" + controllerAction.ActionName; }); });
默认定义的token,已经注释了
public class AddAuthTokenHeaderParameter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { operation.Parameters = operation.Parameters ?? new List<OpenApiParameter>(); //MemberAuthorizeAttribute 自定义的身份验证特性标记 var isAuthor = operation != null && context != null; if (isAuthor) { //in query header operation.Parameters.Add(new OpenApiParameter() { Name = "token", In = ParameterLocation.Header, //query formData .. Description = "身份验证", Required = false, Schema = new OpenApiSchema { Type = "Bearer" } }); } } }
Configure中
if (env.IsEnvironment("dev")) { app.UseSwagger(c => { c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { var updatedPaths = new OpenApiPaths(); foreach (var entry in swaggerDoc.Paths) { updatedPaths.Add( entry.Key.Replace("v{version}", swaggerDoc.Info.Version), entry.Value); } swaggerDoc.Paths = updatedPaths; }); }); //app.UseSwaggerUI(c => //{ // c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api V1"); // c.InjectJavascript(Path.Combine(AppContext.BaseDirectory), "/Swagger/swagger.js"); //}); app.UseKnife4UI(c => { c.RoutePrefix = string.Empty; ; // serve the UI at root c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api V1"); }); app.UseDeveloperExceptionPage(); } else { app.UseHsts(); }
对应显示
对了,这个是基于.net core2.2,示例是.net core