Search code examples
c#asp.net-web-api

How to return a file using Web API?


I am using ASP.NET Web API.
I want to download a PDF with C# from the API (that the API generates).

Can I just have the API return a byte[]? and for the C# application can I just do:

byte[] pdf = client.DownloadData("urlToAPI");? 

and

File.WriteAllBytes()?

Solution

  • Better to return HttpResponseMessage with StreamContent inside of it.

    Here is example:

    public HttpResponseMessage GetFile(string id)
    {
        if (String.IsNullOrEmpty(id))
            return Request.CreateResponse(HttpStatusCode.BadRequest);
    
        string fileName;
        string localFilePath;
        int fileSize;
    
        localFilePath = getFileFromID(id, out fileName, out fileSize);
           
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    
        return response;
    }
    

    UPDATE from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).