using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Learn.Archives.Core.Common.Expand { public static class SwaggerExpand { public static void AddSwaggerExpand(this IServiceCollection s,string name="") { s.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Description = name }); c.OperationFilter(); //按Http类型排序 c.OrderActionsBy(o => o.GroupName); c.DocInclusionPredicate((docName, apiDesc) => { try { if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo)) return false; var versions = methodInfo.DeclaringType.GetCustomAttributes(true) .OfType().Select(attr => attr.GroupName); if (docName.ToLower() == "v1" && versions.FirstOrDefault() == null) return true; return versions.Any(v => v.ToString() == docName); } catch (Exception ex) { throw; } }); //添加全局安全性需求 c.AddSecurityRequirement(new OpenApiSecurityRequirement{ { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" } }, Array.Empty() } }); //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。 c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme { Description = "使用JWT授权头。示例:\"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, //内容为以 bearer开头 Scheme = "bearer", BearerFormat = "JWT" }); DirectoryInfo dirs = new DirectoryInfo(AppContext.BaseDirectory); FileInfo[] files = dirs.GetFiles("*.xml"); foreach (var path in files) { c.IncludeXmlComments(path.FullName); } }); //s.AddSwaggerGenNewtonsoftSupport(); } } class SwaggerFileUploadFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormCollection))) { Dictionary schema = new Dictionary(); schema["fileName"] = new OpenApiSchema { Description = "选择上传文件", Type = "string", Format = "binary" }; Dictionary content = new Dictionary(); content["multipart/form-data"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = schema } }; operation.RequestBody = new OpenApiRequestBody() { Content = content }; } } } }