How to swagger-document an ASP.NET Core action which reads Request.Body directly

Viewed 2154

I have a Controller action method which reads the Request.Body directly (instead of using File) for streaming and other purposes. The problem is there is no model binding and therefore Swagger doesn't document the contract. For example:

[HttpPost("upload")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync()
{
  // Read from Request.Body manually, expecting content type to be multipart/*
  return Ok();
}

When loading Swagger UI, there is no way to upload a file, etc.

Is there any way to support this with attributes in ASP.NET Core?

1 Answers

The API:

 [HttpPost]  
    public async Task<IActionResult> Post(  
        [FromForm(Name = "myFile")]IFormFile myFile)  
    {  
            using (var fileContentStream = new MemoryStream())  
            {  
                await myFile.CopyToAsync(fileContentStream);  
                await System.IO.File.WriteAllBytesAsync(Path.Combine(folderPath, myFile.FileName), fileContentStream.ToArray());  
            }  
            return CreatedAtRoute(routeName: "myFile", routeValues: new { filename = myFile.FileName }, value: null); ;  
    }  

Operation filter

public class SwaggerFileOperationFilter : IOperationFilter  
{  
    public void Apply(Operation operation, OperationFilterContext context)  
    {  
        if (operation.OperationId == "Post")  
        {  
            operation.Parameters = new List<IParameter>  
            {  
                new NonBodyParameter  
                {  
                    Name = "myFile",  
                    Required = true,  
                    Type = "file",  
                    In = "formData"  
                }  
            };  
        }  
    }  
}  

Startup- ConfigureServices

services.AddSwaggerGen(  
    options =>  
    {  
        options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API", Version = "v1" });  

        options.OperationFilter<SwaggerFileOperationFilter>();  
    });  

The result in swagger UI: enter image description here

The source is:enter link description here

Related