简体   繁体   中英

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

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?

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: 在此处输入图像描述

The source is: enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM