首页 > Windows开发 > 详细

.net framework webapi swagger 上传文件

时间:2021-04-28 14:43:11      阅读:22      评论:0      收藏:0      [点我收藏+]

参考:how to get swashbuckle to generate parameter type "form" for testing APIs that need a file upload? · Issue #120 · domaindrivendev/Swashbuckle.WebApi (github.com)

技术分享图片

 

 

 

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);

        }

 

技术分享图片

 

.net framework webapi swagger 上传文件

原文:https://www.cnblogs.com/wangx036/p/14713472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!