PDF file download


I’m wondering what the best method is to allow downloading a PDF file via an API endpoint

    public object Get(GetDocumentPdfRequest request)
        var bytes = ...

        return new HttpResult(bytes, "application/pdf");

What about this approach?

Is there a better return type than “object”?

Is it good to set the contenttype to “application/pdf” or better to “application/octet-stream”?


The return type of Service methods have no effect, you should instead use the IReturn<T> interface marker on your Request DTOs to annotate the response of your API so its type information is available to clients, i.e:

public class GetDocumentPdfRequest : IReturn<byte[]> {}

That will return the PDF bytes in the HTTP Response body with an application/pdf Content-Type.

return new HttpResult(bytes, "application/pdf");

Although if you want the response to prompt the user to save the download you should send Content-Disposition Response Headers of which there’s convenience constructors when returning a file, e.g:

return new HttpResult(new FileInfo(filePath), asAttachment:true);

Or when using the Virtual Files Provider:

return new HttpResult(VirtualFileSources.GetFile(virtualPath), asAttachment:true);

Which Mime Type to use ultimately depends on the client receiving it, both should yield similar behavior to prompt the user to download, but generally it’s likely better to be more specific about the response and go with application/pdf.

Thanks a lot!

So you would stay with?

public object Get(GetDocumentPdfRequest request)

Yes my preference is to always object or Task<object> return types so it’s clear that the type information for the API is only maintained in the one place where it matters i.e. IReturn<T>.

Is the filedownload supposed to work with SwaggerUI or API Explorer?

I only get an empty pdf.

Neither, web UIs can’t really do anything with binary files, use the browser or a HTTP Client to download it.