Пишем код

Заметки о .net разработке

How to make Swagger correctly handle file uploads (IFormFile) in Asp.Net Core

without comments

I love Swagger (OpenAPI). It’s a really nice way to share your API definitions, and it is so easy to integrate it into ASP.Net Core applications, that there’s literally no excuse not to use it.
The only glitch in Swagger’s integration is the lack of IFormFile support. So, if you’d like to upload a file you typically write the following action:

<br />
[HttpPost()]<br />
public IActionResult UploadFile(IFormFile file)<br />

And that’s how it’s gonna be displayed in Swagger-UI (the real problem is, of course, in wrong swagger.json definition). As you could see, there’s everything but an ability to upload a file (actually, Swagger exposed all properties of IFormFile, which is completely useless).
Swagger

There’s a nice discussion on Stackoverflow regarding this subject, and a couple of answers that solve the problem either via hardcoding or putting an attribute on an action. That didn’t sound like a generic solution for me, so I went down and implemented an Operation Filter that fixes the issue without any additional work.
The integration is quite simple (as with any other Swagger filter)

<br />
services.AddSwaggerGen(c => c.OperationFilter<FileUploadOperation>());<br />

And here’s the actual filter. It handles IFormFile action parameters, IFormFile within other classes and even arrays(or any IEnumerables) of IFormFile.

<br />
    /// </p>
<summary>
    /// adds an ability to upload files via Swagger (and autogenerated js client)<br />
    /// </summary>
<p>    public class FileUploadOperation : IOperationFilter<br />
    {<br />
        public void Apply(Operation operation, OperationFilterContext context)<br />
        {<br />
            if (context.ApiDescription.HttpMethod != "POST")<br />
                return;</p>
<p>            if (operation.Parameters == null)<br />
                operation.Parameters = new List<IParameter>();</p>
<p>            var isFormFileFound = false;</p>
<p>            //try to find IEnumerable<IFormFile> parameters or IFormFile nested in other classes<br />
            foreach (var parameter in operation.Parameters)<br />
            {<br />
                if (parameter is NonBodyParameter nonBodyParameter)<br />
                {<br />
                    var methodParameter =<br />
                    context.ApiDescription.ParameterDescriptions.FirstOrDefault(x => x.Name == parameter.Name);<br />
                    if (methodParameter != null)<br />
                    {<br />
                        if (typeof(IFormFile).IsAssignableFrom(methodParameter.Type))<br />
                        {<br />
                            nonBodyParameter.Type = "file";<br />
                            nonBodyParameter.In = "formData";<br />
                            isFormFileFound = true;<br />
                        }<br />
                        else if (typeof(IEnumerable<IFormFile>).IsAssignableFrom(methodParameter.Type))<br />
                        {<br />
                            nonBodyParameter.Items.Type = "file";<br />
                            nonBodyParameter.In = "formData";<br />
                            isFormFileFound = true;<br />
                        }<br />
                    }<br />
                }<br />
            }</p>
<p>            //try to find IFormFile parameters of method<br />
            var formFileParameters = context.ApiDescription.ActionDescriptor.Parameters<br />
                .Where(x => x.ParameterType == typeof(IFormFile)).ToList();<br />
            foreach (var apiParameterDescription in formFileParameters)<br />
            {<br />
                operation.Parameters.Add(new NonBodyParameter<br />
                {<br />
                    Name = apiParameterDescription.Name,<br />
                    In = "formData",<br />
                    Description = "Upload File",<br />
                    Required = true,<br />
                    Type = "file"<br />
                });<br />
            }</p>
<p>            if (formFileParameters.Any())<br />
            {<br />
                foreach (var propertyInfo in typeof(IFormFile).GetProperties())<br />
                {<br />
                    var parametersWithTheSameName = operation.Parameters.Where(x => x.Name == propertyInfo.Name);<br />
                    operation.Parameters.RemoveRange(parametersWithTheSameName);<br />
                }<br />
            }</p>
<p>            if (isFormFileFound)<br />
                operation.Consumes.Add("multipart/form-data");<br />
        }<br />
    }<br />

Опубликовать в Facebook
Опубликовать в Google Plus

Written by Shaddix

Август 28th, 2018 at 10:48 дп

Leave a Reply