.Net Core之Swagger

.Net Core之Swagger

WebApi + Swagger是绝配,这里主要使用Swashbuckle和NSwag

  • .Net Core WebApi集成Swagger主要使用Swashbuckle,但是Swashbuckle得页面真的比较卡慢,这时候使用NSwag的页面明显流畅得多:

    public static class SwaggerExtension
    {
        public static void AddMySwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                //需要项目启动xml生成功能,swagger可以自动提取注释
                c.SwaggerDoc("v1", new Info { Title = "XX API", Version = "v1" });
                var filePath = Path.Combine(AppContext.BaseDirectory, "xx.xml");
                c.IncludeXmlComments(filePath, true);
                //默认的api排序不是按照字母来的,可自定义IDocumentFilter重排序
                c.DocumentFilter<TagReOrderDocumentFilter>();
                //默认情况下没法识别文件上传,可自定义IOperationFilter提供上传文件的功能
                c.OperationFilter<FileUploadOperation>();
                //JWT认证功能
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Name = "Authorization",
                    In = "header",
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
                    Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", new string[] { } }
                });
    
                c.CustomSchemaIds(x => x.FullName);
            });
        }
    
        public static void UseMySwagger(this IApplicationBuilder app)
        {
            app.UseSwagger();
            //注意:这里用的是NSwag的UI,Swashbuckle的页面不够流畅
            app.UseSwaggerUi3WithApiExplorer(settings =>
            {
                settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
            });
        }
    }
    
  • 相关自定义功能如下:

    //保证api按名称有序排列
    public class TagReOrderDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Tags = swaggerDoc.Tags.OrderBy(tag => tag.Name).ToList();
        }
    }
    
    //文件上传属性标识,用于api
    [AttributeUsage(AttributeTargets.Method)]
    public class FileUploadAttribute : Attribute
    {
    }
    //添加文件上传功能
    public class FileUploadOperation : IOperationFilter
    {
        private static readonly string[] fileParameters = new[] { "ContentType", "ContentDisposition", "Headers", "Length", "Name", "FileName" };
    
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var operationHasFileUploadButton = context.MethodInfo.GetCustomAttributes<FileUploadAttribute>().Any();
    
            if (!operationHasFileUploadButton)
            {
                return;
            }
    
            operation.Consumes.Add("multipart/form-data");
    
            RemoveExistingFileParameters(operation.Parameters);
    
            operation.Parameters.Add(new NonBodyParameter
            {
                Name = "file",
                Required = true,
                In = "formData",
                Type = "file",
                Description = "待上传文件"
            }
            );
        }
    
        private void RemoveExistingFileParameters(IList<IParameter> operationParameters)
        {
            foreach (var parameter in operationParameters.Where(p => p.In == "query" && fileParameters.Contains(p.Name)).ToList())
            {
                operationParameters.Remove(parameter);
            }
        }
    }
    
posted @ 2019-03-16 13:35  shadowxs  阅读(145)  评论(0)    收藏  举报