chris31389
chris31389

Reputation: 9356

Return type of a file for Swagger documentation with dotnet core

I'm using Swagger for dotnet core to document my dotnet core Web API.

I've read the documentation telling me that I need to add [ProducesResponseType(typeof(XXXXX),200)] above the controller methods to help swagger determine the response type of the method.

I've got a controller method that returns a file and i'm trying to work out how I can tell swagger i'm returning a file.

public class DocumentController : Controller
{
    private readonly IDocumentService _documentService;

    public DocumentController(IDocumentService documentService)
    {
        _documentService = documentService;
    }

    [HttpGet("{documentId}", Name= DocumentRoutes.Document)]
    [ProducesResponseType(typeof(XXXXX), 200)] // <== What goes here?
    public async Task<IActionResult> GetDocument(Guid documentId)
    {
        DocumentAdto documentAdto = await _documentService.GetAsync(documentId);
        return File(documentAdto.DocumentBytes, documentAdto.ContentType, documentAdto.Name);
    }
}

Does anyone have any ideas?

I've thought about byte[] but that just says the return type is "byte".

Upvotes: 17

Views: 18349

Answers (2)

Player One
Player One

Reputation: 617

If you don't know the content type at compile time (i.e. the endpoint can dynamically serve multiple content types), then

[ProducesResponseType(typeof(FileResult), (int)HttpStatusCode.OK)]

describes the type returned by the return File(... statement.

Upvotes: 1

Moho
Moho

Reputation: 16498

What you need is the ProducesAttribute and specify the content type as the parameter (e.g. "application/pdf" for a PDF file).

Edit: it appears Swagger may not pick up on the ProducesAttribute. My suggestion would then be to leave the Type unset for ProducesResponseType and add a /// <response code="200">Returns the requested file</response> comment to the method.

Upvotes: 18

Related Questions