首页 文章

如何在.NET核心web api中添加上传按钮以显示UI?

提问于
浏览
2

我有一个带有swagger的ASP.net核心Web API(使用swashbuckle) .

Web API中的一个操作是文件上载操作:

[Produces("application/json")]
[Route("[controller]")]
public class FilesController : Controller
{
    [HttpPost]
    public void Post(IFormFile file)
    {
        ...
    }
}

当我在swagger UI中查找该动作时,让我填写 IFormFile 的所有字段,这不是我想要测试我的API .

So how can I add an upload button to the Swagger UI?

2 回答

  • 0

    首先添加一个使用multipart formdata的操作过滤器 .

    public class FileUploadOperation : IOperationFilter
    {
        private readonly IEnumerable<string> _actionsWithUpload = new []
        {
            //add your upload actions here!
            NamingHelpers.GetOperationId<FilesController>(nameof(FilesController.Post))
        };
    
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (_actionsWithUpload.Contains(operation.OperationId) )
            {
                operation.Parameters.Clear();
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "file",
                    In = "formData",
                    Description = "Upload File",
                    Required = true,
                    Type = "file"
                });
                operation.Consumes.Add("multipart/form-data");
            }
        }
    }
    
        /// <summary>
        /// Refatoring friendly helper to get names of controllers and operation ids
        /// </summary>
        public class NamingHelpers
        {
            public static string GetOperationId<T>(string actionName) where T : Controller => $"{GetControllerName<T>()}{actionName}";
    
            public static string GetControllerName<T>() where T : Controller => typeof(T).Name.Replace(nameof(Controller), string.Empty);
        }
    

    现在您应该将您的操作添加到 _actionWithUpload 数组!请注意,我添加extesnions只是为了有一个重构友好的过滤器 .

    最后但并非最不重要的是,确保将操作过滤器添加到swagger的选项中 . 所以将 options.OperationFilter<FileUploadOperation>(); 添加到你的swagger选项并完成 .

    完整示例:

    services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(Version, new Info
                    {
                        Title = Title,
                        Version = Version                        
                    }                
                );
                var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, $"{_webApiAssemblyName}.xml");
                options.IncludeXmlComments(filePath);
                options.DescribeAllEnumsAsStrings();
    //this is the step where we add the operation filter
                options.OperationFilter<FileUploadOperation>();
            });
    
  • 3

    除了@ Nick的回答,我还要为AspNet core 2进行2次更改 .

    1]更新了GetOperationId()

    现在所有的operationIds都包含API前缀以及后缀中的Method . 所以我在ActionName中静态添加了API和Post .

    public static string GetOperationId<T>(string actionName) where T : ControllerBase => $"Api{GetControllerName<T>()}{actionName}Post";
    

    2]仅删除文件参数

    我想删除文件参数,而不是删除该操作的所有参数 .

    var fileParameter = operation.Parameters.FirstOrDefault(x => x.Name == "file" && x.In == "body");
    if (fileParameter != null)
    {
        operation.Parameters.Remove(fileParameter);
        ...
    }
    

相关问题