.netCore Swagger 文件上传的友好提示

本人使用的是ABP netcore +Swagger环境。
在这之前,网上搜索到的解决方案都没有解决我的问题,swaggerUI上IFromFile内部的属性都展示到swagger上了。
网上解决的方法大同小异,在这就贴一篇作为比较http://www.cnblogs.com/intotf/p/10075162.html
使用效果前:

使用后效果:

话不多说,直接上代码
Swagger选项过滤器代码
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace ZGBPurchase.Web.Host
{
    public class SwaggerFileUploadFilter : IOperationFilter
    {
        private static readonly string[] FormFilePropertyNames =
        typeof(IFormFile).GetTypeInfo().DeclaredProperties.Select(x => x.Name).ToArray();
        public void Apply(Operation operation, OperationFilterContext context)
        {

            if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
               !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList();

            if (fileParameters.Count < 0)
            {
                return;
            }

            foreach (var fileParameter in fileParameters)
            {
                var formFileParameters = operation
                .Parameters
                .OfType<NonBodyParameter>()
                .Where(x => FormFilePropertyNames.Contains(x.Name))
                .ToArray();
                foreach (var formFileParameter in formFileParameters)
                {
                    operation.Parameters.Remove(formFileParameter);
                }

                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = fileParameter.Name,
                    In = "formData",
                    Description = "文件上传",
                    Required = true,
                    Type = "file"
                });
                operation.Consumes.Add("multipart/form-data");


            }
        }
    }
}

  对startup.cs swagger配置修改

猜你喜欢

转载自www.cnblogs.com/huanfion/p/10712413.html
今日推荐