1.
1 public class ImportFileParamType : IOperationFilter 2 { 3 [AttributeUsage(AttributeTargets.Method)] 4 public sealed class SwaggerFormAttribute : Attribute 5 { 6 public SwaggerFormAttribute(string name, string description) 7 { 8 Name = name; 9 Description = description; 10 } 11 public string Name { get; private set; } 12 13 public string Description { get; private set; } 14 } 15 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) 16 { 17 var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerFormAttribute>(); 18 foreach (var attr in requestAttributes) 19 { 20 operation.parameters = new List<Parameter> 21 { 22 new Parameter 23 { 24 description = attr.Description, 25 name = attr.Name, 26 @in = "formData", 27 required = true, 28 type = "file", 29 } 30 }; 31 operation.consumes.Add("multipart/form-data"); 32 } 33 } 34 }
2.SwaggerConfig中添加
c.OperationFilter<ImportFileParamType>();
3.controller
[ImportFileParamType.SwaggerFormAttribute("ImportExcel", "Upload Excel file")] [HttpPost] public async Task<ApiResult<List<object>>> ReadInProp() { if (HttpContext.Current.Request.Files.Count <= 0) return null; var uploadFile = HttpContext.Current.Request.Files[0]; if (uploadFile == null || uploadFile.InputStream.Length == 0) return null; var ds = NPOIHelper.RenderDataSetFromExcel(uploadFile.InputStream, new[] { 0 }, 0); var dt = ds.Tables[0]; List<object> objList = new List<object>(); foreach (DataRow dr in dt.Rows) { objList.Add(new { Id = dr[0].ToString(), Value = dr[3].ToString() }); } return Success(data: objList); }